如果我在Ansible中启动一台EC2实例(或一组实例),如何稍后引用该实例(或集合)并终止它们?这是跨playbook的。因此,在一个playbook中,我已经启动了一个实例,然后稍后,我想使用另一个playbook终止这些实例。谢谢。
- name: terminate single instance
hosts: all
tasks:
- action: ec2_facts
- name: terminating single instance
local_action:
module: ec2
state: 'absent'
region: us-east-1
instance_ids: "{{ ansible_ec2_instance_id }}"
终止位于 instance.example.com 地址的实例:
$ ansible-playbook -i instance.example.com, terminate.yml
ec2 facts module将查询实例上的元数据服务以获取实例ID。使用ec2模块按其ID终止实例。
请注意,ec2_facts模块需要在您要终止的实例上运行,并且您可能希望使用清单文件或动态清单通过标记查找实例而不是通过主机名寻址。
如果我们要使用动态清单,我建议在使用 create.yml 创建实例时,使用 ec2 模块的 count_tags 和 exact_count:
---
- hosts: localhost
connection: local
gather_facts: false
vars_files: { ./env.yml }
tasks:
- name: Provision a set of instances
ec2:
instance_type: "{{ item.value.instance_type }}"
image: "{{ image }}"
region: "{{ region }}"
vpc_subnet_id: "{{ item.value.vpc_subnet_id }}"
tenancy: "{{ tenancy }}"
group_id: "{{ group_id }}"
key_name: "{{ key_name }}"
wait: true
instance_tags:
Name: "{{ env_id }}"
Type: "{{ item.key }}"
count_tag:
Type: "{{ item.key }}"
exact_count: "{{ item.value.count }}"
with_dict: "{{ servers }}"
register: ec2
env.yml 文件包含了所有变量,以及服务器字典:
---
env_id: JaxDemo
key_name: JaxMagicKeyPair
image: "ami-xxxxxxxx"
region: us-east-1
group_id: "sg-xxxxxxxx,sg-yyyyyyyy,sg-zzzzzzzz"
tenancy: dedicated
servers:
app:
count: 2
vpc_subnet_id: subnet-xxxxxxxx
instance_type: m3.medium
httpd:
count: 1
vpc_subnet_id: subnet-yyyyyyyy
instance_type: m3.medium
oracle:
count: 1
vpc_subnet_id: subnet-zzzzzzzz
instance_type: m4.4xlarge
exact_count: "{{ item.value.count }}"
使用
exact_count: 0
我将扩展jarv的答案,并提供一个工作示例,您可以在其中使用Ansible Playbook终止单个或一组服务器。
假设您想要终止主机文件中删除组下的一个或多个实例:
[delete]
X.X.X.X # IP address of an EC2 instance
---
- hosts: delete
gather_facts: True
user: ubuntu
sudo: True
tasks:
# fetch instance data from the metadata servers in ec2
- ec2_facts:
# just show the instance-id
- debug: msg= "{{ hostvars[inventory_hostname]['ansible_ec2_instance_id'] }}"
- hosts: delete
gather_facts: True
connection: local
vars:
region: "us-east-1"
tasks:
- name: destroy all instances
ec2: state='absent'
region={{ region }}
instance_ids={{ item }}
wait=true
with_items: hostvars[inventory_hostname]['ansible_ec2_instance_id']
ansible-playbook -i hosts ec2_terminate.yml
在创建这些实例时,请确保对它们进行唯一标识/标记。 然后在以下运行中,您可以使用动态清单脚本来填充您的主机列表,如此处所示 http://docs.ansible.com/intro_dynamic_inventory.html,然后终止与您的标记匹配的实例。