如何在Ansible中的嵌套json中写入变量/硬代码值?

时间:2019-04-30 14:54:11

标签: ansible jinja2

我正在尝试创建一个具有硬代码值的json文件作为嵌套json中的输出,但是第二次播放将覆盖第一个播放值,那么我们有什么最佳选择吗?

我已经尝试过使用to_nice_json模板将变量复制到json文件中,但是无法在imported_var中保留多个变量值以复制到json文件中

---
- hosts: localhost
  connection: local
  gather_facts: false

  tasks:
  - name: load var from file
    include_vars:
      file: /tmp/var.json
      name: imported_var

  - name: Checking mysqld status
    shell: service mysqld status
    register: mysqld_stat
    ignore_errors: true

  - name: Checking mysqld status
    shell: service httpd status
    register: httpd_stat
    ignore_errors: true

  - name: append mysqld status to output json
    set_fact:
     imported_var: "{{ imported_var | combine({ 'status_checks':[{'mysqld_status': (mysqld_stat.rc == 0)|ternary('good', 'bad') }]})}}"

# - name: write var to file
 #   copy:
  #    content: "{{ imported_var | to_nice_json }}"
   #   dest: /tmp/final.json

  - name: append httpd status to output json
    set_fact:
      imported_var: "{{ imported_var| combine({ 'status_checks':[{'httpd_status': (httpd_stat.rc == 0)|ternary('good', 'bad') }]})}}"

 # - debug:
  #    var: imported_var

  - name: write var to file
    copy:
      content: "{{ imported_var | to_nice_json }}"
      dest: /tmp/final.json

预期结果:

{
    "status_checks": [
        {
            "mysqld_status": "good"
            "httpd_status": "good"
        }
    ]
}

实际结果:

{
    "status_checks": [
        {
            "httpd_status": "good"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

您正在尝试执行Ansible并不是真正擅长的那种数据操作。每当您尝试修改现有变量时(尤其是在尝试设置嵌套值时),都会使生活变得复杂。话虽如此,可以做您想做的事情。例如:

---
- hosts: localhost
  gather_facts: false
  vars:
    imported_var: {}

  tasks:
    - name: Checking sshd status
      command: systemctl is-active sshd
      register: sshd_stat
      ignore_errors: true

    - name: Checking httpd status
      command: systemctl is-active httpd
      register: httpd_stat
      ignore_errors: true

    - set_fact:
        imported_var: "{{ imported_var|combine({'status_checks': []}) }}"

    - set_fact:
        imported_var: >-
          {{ imported_var|combine({'status_checks':
          imported_var.status_checks + [{'sshd_status': (sshd_stat.rc == 0)|ternary('good', 'bad')}]}) }}

    - set_fact:
        imported_var: >-
          {{ imported_var|combine({'status_checks':
          imported_var.status_checks + [{'httpd_status': (httpd_stat.rc == 0)|ternary('good', 'bad')}]}) }}

    - debug:
        var: imported_var

在我的系统上(正在运行sshd但未运行httpd,这将输出:

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "imported_var": {
        "status_checks": [
            {
                "sshd_status": "good"
            }, 
            {
                "httpd_status": "bad"
            }
        ]
    }
}

您可以通过重组数据来极大地简化剧本。将status_checks设为顶级变量,而不是将其作为列表,而应将其作为将服务名称映射到相应状态的字典。将其与一些循环结合起来,最终会得到非常简单的东西:

---
- hosts: localhost
  gather_facts: false

  tasks:

    # We can use a loop here instead of writing a separate task
    # for each service.
    - name: Checking service status
      command: systemctl is-active {{ item }}
      register: services
      ignore_errors: true
      loop:
        - sshd
        - httpd

    # Using a loop in the previous task means we can use a loop
    # when creating the status_checks variable, which again removes
    # a bunch of duplicate code.
    - name: set status_checks variable
      set_fact:
        status_checks: "{{ status_checks|default({})|combine({item.item: (item.rc == 0)|ternary('good', 'bad')}) }}"
      loop: "{{ services.results }}"

    - debug:
        var: status_checks

以上将输出:

TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] => {
    "status_checks": {
        "httpd": "bad", 
        "sshd": "good"
    }
}

如果您确实想将此信息添加到imported_var中,则可以在单个任务中完成:

- set_fact:
    imported_var: "{{ imported_var|combine({'status_checks': status_checks}) }}"