Ansible:使用模板获取价值

时间:2018-08-28 04:07:34

标签: ansible jinja2

这是我的json:

{
"appId": "usecase-watchlist",
"instanceName": "usecase-watchlist-instance",
"node": "master",
"configuration": {
   "videoSensorInstance": {
       "node": "worker",
       "configuration": {
           "cameraSensor": 1
       }
   },
   "faceDetectionInstance": {
       "node": "worker",
       "configuration": {
           "cameraSensor": 1,
           "database": {
               "name": "facedetection_db",
               "dbmsName": "mongodb",
               "type": "mongodb",
               "username": "fb719a05",
               "password": "b5f64277"
          }
       }
   },
   "alerts-manager-instance": {
       "node": "worker",
       "configuration": {
         "database": {
            "name": "alerts_db",
            "dbmsName": "mongodb",
            "type": "mongodb",
            "username": "fb719a05",
            "password": "b5f64277"
          }
       }
     }
   }
 }

我有一个名为app_spec_contents的变量,其中存在此​​json的内容。

我还有一个字典app_instances,其中包含:

     app_instances contains :

    "app_instances": {
    "alerts-manager": "alertsManagerInstance",
    "video-sensor": "videoSensorInstance",...
    }

现在我在下面的戏剧中写作,这将创建给定形式的地图:

#Get the configuration of instances one by one
- name: Get the configuration of instances one by one
  set_fact:
    app_configurations: "{{ app_configurations|default({}) | combine( { item.key:{ item.key + '_db_connection_string': app_spec_contents.configuration } } ) }}"
  with_items : "{{ app_instances|dict2items }}"

我想要以下结果的字典:

    {"alerts-manager" : { 
        "alerts-manager-instance_db_connection_string" : 
 "mongodb://fb719a05:b5f64277@172.17.0.2:27017/alerts_db",
         "name":"alerts_db" 
        },
     ... } ---> for every item in dict if database is there, like in one instance.

此外,如果app_spec_contents{{ item.value }}中存在的实例中包含configuration.database,则将写入when条件。

请帮助。

1 个答案:

答案 0 :(得分:0)

此问题已解决: 以下是正确的Yaml:

- name: Get the configuration of instances one by one
  set_fact:
    app_configurations: "{{ app_configurations|default({}) | combine( { item.key:{ item.key + '_db_connection_string': app_spec_contents.configuration[item.value].configuration.database.dbmsName + '://' + app_spec_contents.configuration[item.value].configuration.database.username + ':' + app_spec_contents.configuration[item.value].configuration.database.password + '@172.17.0.2:27017/' + app_spec_contents.configuration[item.value].configuration.database.name , item.key + '_db_name' : app_spec_contents.configuration[item.value].configuration.database.name } } ) }}"
  when: app_spec_contents.configuration[item.value].configuration.database is defined and app_spec_contents.configuration[item.value].configuration.database.dbmsName=="mongodb"
  with_items : "{{ app_instances|dict2items }}"
相关问题