combo variables

2017-08-16

Ansible’s jinja makes for some weird ass syntax sometimes, but you can do basic stuff without having to dip into python directly, like combining lists and dictionaries from other hosts

With an inventory like this

[fooservers]
foohost1 ansible_host=localhost
foohost2 ansible_host=localhost
foohost3 ansible_host=localhost

list example

---
- hosts: fooservers
  connection: local
  gather_facts: false
  tasks:
    - name: do an echo 
      shell: echo "hideho from {{ansible_host}} aka {{inventory_hostname}}" it is now `date` here
      register: echoout
    - name: ad the hostname to the line
      set_fact:
        host_echo: "{{host_echo|default([])|union([ inventory_hostname+' -> '+item ])}}"
      with_items: "{{echoout.stdout_lines}}"

- hosts: localhost
  connection: local
  gather_facts: false
  tasks: 
    - name: create a single list
      set_fact:
        unionlist: "{{unionlist|default([])|union(hostvars[item].host_echo)}}"
      with_items: "{{groups['fooservers']}}"
      no_log: True
    - debug: var=unionlist

Gets you

ok: [localhost] => {
    "unionlist": [
        "foohost1 -> hideho from localhost aka foohost1 it is now Thu Aug 17 04:37:35 SAST 2017 here",
        "foohost2 -> hideho from localhost aka foohost2 it is now Thu Aug 17 04:37:35 SAST 2017 here",
        "foohost3 -> hideho from localhost aka foohost3 it is now Thu Aug 17 04:37:35 SAST 2017 here"
    ]
}

dictionary example

----
- hosts: fooservers
  connection: local
  gather_facts: false
  tasks:
    - name: do an echo 
      shell: echo "hideho from {{ansible_host}} aka {{inventory_hostname}}" \\nit is now `date` here
      register: echoout
    - name: ad the hostname to the variable
      set_fact:
        host_echo: '{ "ahost-{{inventory_hostname}}": {{echoout.stdout_lines|to_json}} }'

- hosts: localhost
  connection: local
  gather_facts: false
  tasks: 
    - name: combine the dicts
      set_fact:
        combineddict: "{{combineddict|default({})|combine({'combohost-'+item: hostvars[item].host_echo})}}"
      with_items: "{{groups['fooservers']}}"
      no_log: True
    - debug: var=combineddict

Gets you

(PS: take note of that weird ass nested way to get the hostname into the key of the host_echo variable [second task, first play])

ok: [localhost] => {
    "combineddict": {
        "combohost-foohost1": {
            "ahost-foohost1": [
                "hideho from localhost aka foohost1 ",
                "it is now Thu Aug 17 05:10:31 SAST 2017 here"
            ]
        },
        "combohost-foohost2": {
            "ahost-foohost2": [
                "hideho from localhost aka foohost2 ",
                "it is now Thu Aug 17 05:10:31 SAST 2017 here"
            ]
        },
        "combohost-foohost3": {
            "ahost-foohost3": [
                "hideho from localhost aka foohost3 ",
                "it is now Thu Aug 17 05:10:31 SAST 2017 here"
            ]
        }
    }
}