引用刚才在Ansible中创建的EC2资源的实例ID

时间:2017-06-21 21:46:42

标签: amazon-ec2 ansible

我很难引用我刚刚创建的EC2资源的实例ID。在我创建它之后,我会立即终止它。我的代码如下:

谢谢你, 比尔

---
- name: Example of provisioning servers
  hosts: 127.0.0.1

  connection: local
  tasks:
   - name: set_fact1
     set_fact: foo = 1

   - name: Create security group
     local_action:
       module: ec2_group
       name: ep2
       description: Access to the Episode2 servers
       region: us-east-1
       rules:
         - proto: tcp
           from_port: 22
           to_port: 22
           cidr_ip: 0.0.0.0/0

   - name: Launch instances
     local_action:
       module: ec2
       instance_tags:
        Name: server1
        Env: myenv
       region: us-east-1
       keypair: ansiblekeypair
       group: ep2
       instance_type: m1.small
       image: ami-1aae3a0c
       count: 1
       wait: yes
     register: ec2

   - name: Terminate instances that were previously launched
     ec2:
       state: absent
       region: us-east-1
       instance_ids: "{{ ec2.instance_id[0] }}"
     with_items: ec2

2 个答案:

答案 0 :(得分:5)

您需要引用ec2.instances[0].id

使用- debug: var=ec2任务或使用-vv开关运行playbook以查看已注册变量的详细值并检查可供使用的属性非常有用。

答案 1 :(得分:0)

如果要终止刚启动的实例(假设它们的标签是特定的),您还可以使用exact_count工具:

   exact_count: 0
   count_tag: 
     - Name: server1
     - Env: myenv

根据文件(重点是我的):

exact_count

  

一个整数值,表示应该运行与count_tag参数匹配的实例数。根据此值创建实例或终止

count_tag

  

exact_count一起使用,以确定根据特定标记条件运行的节点数。 [...]

它会给出类似的东西:

- name: Terminate instances
     local_action:
       module: ec2
       instance_tags:
        Name: server1
        Env: myenv
       region: us-east-1
       keypair: ansiblekeypair
       exact_count: 0
       count_tag: 
         - Name: server1
         - Env: myenv
       wait: yes