make inventories from variables

2017-08-16

making an inventory file from something like cloudformation

After you add_host to your hearts content from some inventory spinning up sources like aws

(will have a complete example in the future)

---
- name: create / update stack "{{stack_name}}"
  cloudformation:
    stack_name: "{{stack_name}}"
    state: "present"
    region: "eu-west-1"
    disable_rollback: true
    template: "./cloudformation/{{stack_name}}.template.yml"
    tags:
      Stack: "ansible-cloudformation"
  register: output
- add_host:
    name: "{{stack_name+item.name}}"
    ansible_host: "{{output.stack_outputs[stack_name+item.name+'Public']}}"
    ansible_private: "{{output.stack_outputs[stack_name+item.name+'Private']}}"
    groups: "{{item.group|default(stack_name)}}"
    ansible_ssh_private_key_file: ~/pem/lepempado.pem
    ansible_user: ubuntu
  with_items: "{{vpc.instances}}"

You can dump this dynamic inventory for later use using a template like this..

{% for group in groups %}
[{{group}}]
{% for host in groups[group] %}
{% if not host == 'localhost' %}
{{host}} ansible_host={{hostvars[host]['ansible_host']}} ansible_private={{hostvars[host]['ansible_private']}} ansible_ssh_private_key_file={{hostvars[host]['ansible_ssh_private_key_file']}} ansible_user={{hostvars[host]['ansible_user']}}
{% endif %}
{% endfor %}
{% endfor %}

will land you something like this

[ungrouped]
[firewallstub]
firewallstubswan1 ansible_host=99.18.288.220 ansible_private=10.0.100.15 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
[all]
firewallstubuser1 ansible_host=99.18.80.112 ansible_private=10.0.100.30 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
firewallstubswan1 ansible_host=99.18.288.220 ansible_private=10.0.100.15 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
transituser2 ansible_host=88.253.159.224 ansible_private=10.0.101.19 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
transitswan2 ansible_host=99.215.99.43 ansible_private=10.0.101.15 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
buvpc1user3 ansible_host=99.17.201.154 ansible_private=10.0.102.8 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
[users]
firewallstubuser1 ansible_host=99.18.80.112 ansible_private=10.0.100.30 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
transituser2 ansible_host=88.253.159.224 ansible_private=10.0.101.19 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
buvpc1user3 ansible_host=99.17.201.154 ansible_private=10.0.102.8 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu
[transit]
transitswan2 ansible_host=99.215.99.43 ansible_private=10.0.101.15 ansible_ssh_private_key_file=~/pem/lepempado.pem ansible_user=ubuntu

which you can then later on hack with other playbooks