Tuesday, October 26, 2021

[SOLVED] ansible: obtain private address of all the machine and use it in a jinja template cycling

Issue

Have to collect all the private address of EC2 instance with Ansible take the value and loop in a jinja template

for...
    node {
        name "O=texas,L=Huston,C=USA"
        p2pPort 10008
        rpcSettings {
            address("{{public_ip}}:10009")
            adminAddress("{{public_ip}}:10010")
        }
        rpcUsers = [[user: "user1", "password": "test", "permissions": ["ALL"]]]
    }

Solution

I think you could generate your list via ec2_instance_info module and then loop through that list in the template. So the tasks would be:

- name: grab private ip from ec2
  ec2_instance_info:
    filter:
      "tag:some_tag_key": "some_tag_value"
  register: ec2_instance_info

- name:
  set_fact:
    public_ip_addresses: "{{ ec2_instnace_info | json_query('instances[].public_ip_address') }}"

- name: loop though private ips in template 
  template: 
    src: template_file.j2
    dest: destination

The jinja template would be:

{% for public_ip_address in public_ip_addresses %}
    node {
        name "O=texas,L=Huston,C=USA"
        p2pPort 10008
        rpcSettings {
            address("{{ public_ip_address }}:10009")
            adminAddress("{{ public_ip_address }}:10010")
        }
        rpcUsers = [[user: "user1", "password": "test", "permissions": ["ALL"]]]
    }
{% endfor %}

I have not tested, but in theory I think it would work.



Answered By - azoradm