Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

Ansible: Combine 2 json object with with_item

I have the following playbook:

---
- hosts: localhost
  gather_facts: False
  vars:
    arraylist: []
    host_list: ["abc.cloud.com", "efg.cloud.com"]
    pb_os_family: 'Linux'
    pb_input: '{""pb_os_family"": ""{{ pb_os_family }}""}'
    pb_stuct: '{""server_list"": ""[]""}'
    json_path: '/home/test/'
    pb_json: '{{json_path}}/s_{{ host }}.json'
    pb_final_json: '{{json_path}}/s_final.json'

  tasks:
    - name: Create a json file..
      shell: 'echo -e "{{ pb_input }}" > "{{ pb_json }}"'
      vars:
        host: "{{item}}"
      with_items: "{{host_list}}"

    - name: cat the file
      shell: 'cat "{{pb_json}}"'
      register: wcho_out
      vars:
        host: "{{item}}"
      with_items: "{{host_list}}"

    - debug:
        msg: "{{ item }}"
      with_items: "{{host_list}}"

    - debug:
        msg: "{{ item.stdout }}"
      loop: "{{wcho_out.results}}"

    - name: combine output
      set_fact:
        output: "{{arraylist}} + [ '{{ item.stdout }}' ]"
        #ec2_security_group_names: "{{ ec2_security_group_names }} + [ '{{ item.group_name }}' ]"
      loop: "{{wcho_out.results}}"

    - debug:
        msg: "{{ output }}"

    - name: Create a final json file..
      shell: 'echo -e "{{ output | to_json }}" > "{{ pb_final_json }}"'

Final JSON file (pb_final_json) should contains both the pb_input values, but currently only the last item value were listing.

Current_output:

[{"pb_os_family": "Linux"}]

Expected_output:

[{"pb_os_family": "Linux"},{"pb_os_family": "Linux"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...