简体   繁体   English

Ansible循环通过ec2_instance_facts结果 - diff输出调试vs set_fact

[英]Ansible loop through ec2_instance_facts results - diff output debug vs set_fact

I'm getting different output using the same method in debug vs set_fact. 我在debug和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. 在最初的ec2_instance_facts循环中,输出6个实例。 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). 在调试循环期间获取私有IP,所有6个IP都输出,虽然在2个单独的块中(我猜测从初始循环 - 2在第一个块中输出,然后是剩余的4个)。

However, when using set_fact, I only ever get the first 2 IPs. 但是,当使用set_fact时,我只获得前2个IP。 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. 我猜我正在使它变得比它需要的更难,并且必须正确地使用第一个循环,但是我被卡住了。

I think this can be closed as a duplicate. 我认为这可以作为副本关闭。 I found this answer which is pulled directly from this PR . 我发现这个答案直接来自这个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. 由于提交的代码不再适用于Ansible 2.x,PR最终被关闭,并且解决方法(在答案中公布)被接受为功能性的。

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. 答案是,为清楚起见,基本上如果你使用循环运行set_fact,你需要将该事实传递给后续的 set_fact,然后通过map jinja过滤器从先前设置的事实中创建一个列表。

I've now got 2 lists, due to my initial loop running 2x, but that's a different matter. 由于我的初始循环运行2次,我现在有2个列表,但这是另一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM