从外部文件读取变量

时间:2018-11-01 17:44:30

标签: ansible ansible-2.x

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

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

现在,当我尝试读取变量 out_file control_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

任何建议表示赞赏

1 个答案:

答案 0 :(得分:0)

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

{
  "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"
}