0

I'm getting different output using the same method in debug vs set_fact.

      - name: Get EC2 instances
        ec2_instance_facts:
          filters:
            "tag:Name": "{{ item }}"
        loop:
          - value
          - value
        register: servers

      - debug:
          msg: "{{ item.instances | map(attribute='private_ip_address') | list }}"
        loop:  "{{ servers.results }}"

      - name: Set the private IPs list
        set_fact:
          private_ips: "{{ item.instances | map(attribute='private_ip_address') | list }}"
        loop: "{{ servers.results }}"

      - debug:
          var: private_ips

In the initial ec2_instance_facts loop, 6 instances are output. During the debug loop to get the private IPs, all 6 IPs are output, albeit in 2 separate blocks (I'm guessing from the initial loop - 2 are output in the first block, then the remaining 4).

However, when using set_fact, I only ever get the first 2 IPs. I'm guessing I'm making this more difficult than it needs to be, and it's got to do w/using that first loop correctly, but I'm stuck.

Travis
  • 404
  • 1
  • 4
  • 14
  • i guess you overwrite `private_ips' in every loop. – Can Mar 26 '19 at 13:59
  • @Can - correct: which is why the loop needs to be registered & then passed to yet another set_fact. See my answer below. – Travis Mar 26 '19 at 14:04
  • hmmm, i use jinja expressions. this won't be a real answer but it may help you: `- set_fact:` `private_ips: "{% set private_ips = [] %}{% for item in servers.results %}{% set new_ip=(item.instances | map(attribute='private_ip_address)) %}{{private_ips.append(new_ip)}}{% endfor %}{{private_ips}}"` – Can Mar 26 '19 at 14:05

1 Answers1

0

I think this can be closed as a duplicate. I found this answer which is pulled directly from this PR. The PR was eventually closed as the submitted code was no longer functional with Ansible 2.x, and the workaround (posted in the answer) was accepted as functional.

The answer, for clarity, is basically that if you run set_fact with a loop, you need to then pass that fact to a subsequent set_fact that then creates a list from the previously set fact, passed through the map jinja filter.

I've now got 2 lists, due to my initial loop running 2x, but that's a different matter.

Travis
  • 404
  • 1
  • 4
  • 14