首页 > 解决方案 > 在动态收集的 EC2 实例上运行任务

问题描述

我正在尝试编写一个角色,其任务是过滤掉几个 EC2 实例,将它们添加到清单中,然后停止它们上的 PHP 服务。

这是我已经走了多远,我从这里复制的 add_host 想法:http: //docs.catalystcloud.io/tutorials/ansible-create-x-servers-using-in-memory-inventory.html

我的服务任务似乎没有在目标实例上运行,而是在运行此角色的剧本中指定的主机上运行。

---
- name: Collect ec2 data
 connection: local
 ec2_remote_facts:
     region: "us-east-1"
     filters:
       "tag:Name": MY_TAG
 register: ec2_info
- name: "Add the ec2 hosts to a group"
  add_host: 
    name: "{{ item.id }}"
    groups: foobar
    ansible_user: root
  with_items: "{{ ec2_info.instances }}"

- name: Stop the service
  hosts: foobar
  become: yes
  gather_facts: false
  service: name=yii-queue@1 state=stopped enabled=yes

更新:当我尝试 baptistemm 的建议时,我得到了这个:

PLAY [MAIN_HOST_NAME] ***************************

TASK [ec2-manage : Collect ec2 data] 
*******************************************

ok: [MAIN_HOST_NAME]

TASK [ec2-manage : Add the hosts to a new group] 
*******************************************************

PLAY RECAP **********************************************************

MAIN_HOST_NAME                  : ok=1    changed=0    unreachable=0    failed=0   

更新 #2 - 是的,ec2_remote_tags 过滤器确实返回实例(使用真正的标签值而不是我在这篇文章中输入的假值)。此外,我已经看到了 ec2_instance_facts 但我遇到了一些问题(需要 boto3,尽管我有一个解决方法,但我仍然试图首先解决当前问题)。

标签: amazon-ec2ansible

解决方案


如果您想在一组目标上播放任务,则需要在创建内存中的目标列表后定义一个新的播放add_host(如链接中所述)。所以要做到这一点,你需要这样:

   … # omit the code before

   - name: "Add the ec2 hosts to a group"
     add_host:
       name: "{{ item.id }}"
       groups: foobar
       ansible_user: root
     with_items: "{{ ec2_info.instances }}"

- hosts: foobar
  gather_facts: false
  become: yes
  tasks:

   - name: Stop the service
     hosts: foobar
     service: name=yii-queue@1 state=stopped enabled=yes

推荐阅读