首页 > 解决方案 > Ansible 从外部文件读取变量

问题描述

我将所有 json 格式的变量存储在一个外部文件中,并尝试在剧本中读取这是一个示例文件

{out_file: exp_app_20.xml,  control_file: export_control.xml  }
{out_file: exp_app_21.xml,  control_file: export_control.xml }

现在,当我尝试读取变量out_filecontrol_file时,我找不到合适的方式来读取它。我试过 with_items 和 with_lines 但没有运气

- name: searching for text file

  gather_facts: false
  vars:
   host_tgt: TGT

  hosts: "{{ host_tgt }}"
  tasks:



  - name: get the file contents
    shell: cat /dir/export.prop
    register: my_items

  - debug:
      var: my_items

  - name: Export 
    shell: echo {{ item.out_file }} **---error**

    with_items: my_items.stdout_lines

    register: find_output

  - debug:
      var: find_output

任何建议表示赞赏

标签: ansibleansible-2.x

解决方案


假设您可以更改文件的格式....

{
  "array": [
    { "out_file": "exp_app_20.xml", "control_file": "export_control.xml" },
    { "out_file": "exp_app_21.xml", "control_file": "export_control.xml" }
  ]
}

include_vars然后在您的剧本中,使用...加载文件。

  tasks:

    - include_vars:
        file: /home/jack/test.json
        name: my_items

    - debug:
        var: my_items

    - debug:
        msg: "{{ item.out_file }}"
      with_items: "{{ my_items.array }}"

这给出了这个输出:

TASK [debug] ************************************************************************************************************************
ok: [localhost] => {
    "my_items": {
        "array": [
            {
                "control_file": "export_control.xml", 
                "out_file": "exp_app_20.xml"
            }, 
            {
                "control_file": "export_control.xml", 
                "out_file": "exp_app_21.xml"
            }
        ]
    }
}

TASK [debug] ************************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": "exp_app_20.xml"
}
ok: [localhost] => (item=None) => {
    "msg": "exp_app_21.xml"
}

推荐阅读