该问题可能是由于aws_ec2插件的一些缓存或是标签等原因导致的。我们可以通过在任务中使用“refresh_cache”和“filters”参数来解决该问题。
示例代码:
name: 获取所有符合条件的AWS EC2实例 ec2_instance_facts: region: us-west-2 filters: "tag:Environment": dev "instance-state-name": [running, stopped] register: ec2_facts ignore_errors: True
name: 使用变量过滤实例 set_fact: ec2_instances: "{{ ec2_facts.instances | map(attribute='id') | list }}"
name: 在所有实例上执行命令 hosts: "{{ ec2_instances }}" gather_facts: no tasks:
name: 确保实例已安装Apache become: True yum: name: httpd state: present register: apache_install_status
name: 重启Apache服务 when: apache_install_status.changed become: True service: name: httpd state: restarted
在以上示例中,我们在任务中使用了“refresh_cache”和“filters”参数。通过该方式,我们可以过滤出符合条件的AWS EC2实例,避免了重复实例的问题。