我有一个 ansible 角色,可以使用备份标签为附加到 ec2 实例的所有 ebs 卷(/dev/sdb)拍摄快照。
- name: "take snapshots of vms with backup:yes tag"
hosts: localhost
tasks:
- name: "Gather facts of EC2 instance"
ec2_instance_info:
region: "{{ aws_region }}"
aws_access_key: "{{ ACCESS_KEY }}"
aws_secret_key: "{{ SECRET_ACCESS_KEY }}"
filters:
"tag:Backup": "yes"
register: ec2_facts
- name: set fact
set_fact:
inst_id: "{{ ec2_facts.instances[0].instance_id }}"
- name: "Create snapshot Linux"
ec2_snapshot:
region: "{{ aws_region }}"
aws_access_key: "{{ ACCESS_KEY }}"
aws_secret_key: "{{ SECRET_ACCESS_KEY }}"
instance_id: "{{ inst_id }}"
device_name: "/dev/sdb"
该脚本工作正常,但当同一标签内有多个实例时,它只会拍摄第一个实例的快照。有没有办法为这些标签内的每个实例卷拍摄快照?
当然,您只需要迭代列表而不是使用第一个实例:
- name: "take snapshots of vms with backup:yes tag"
hosts: localhost
tasks:
- name: "Gather facts of EC2 instance"
ec2_instance_info:
region: "{{ aws_region }}"
aws_access_key: "{{ ACCESS_KEY }}"
aws_secret_key: "{{ SECRET_ACCESS_KEY }}"
filters:
"tag:Backup": "yes"
register: ec2_facts
- name: "Create snapshot Linux"
ec2_snapshot:
region: "{{ aws_region }}"
aws_access_key: "{{ ACCESS_KEY }}"
aws_secret_key: "{{ SECRET_ACCESS_KEY }}"
instance_id: "{{ instance.instance_id }}"
device_name: "/dev/sdb"
loop: "{{ ec2_facts.instances }}"
loop_control:
loop_var: instance
顺便说一句,这不是一个角色,而是一本剧本。为了简化代码,您可以将所有模块调用重复的模块参数设置为
module_defaults
:
- name: "take snapshots of vms with backup:yes tag"
hosts: localhost
module_defaults:
ec2_instance_info:
region: "{{ aws_region }}"
aws_access_key: "{{ ACCESS_KEY }}"
aws_secret_key: "{{ SECRET_ACCESS_KEY }}"
tasks:
- name: "Gather facts of EC2 instance"
ec2_instance_info:
filters:
"tag:Backup": "yes"
register: ec2_facts
- name: "Create snapshot Linux"
ec2_snapshot:
instance_id: "{{ instance.instance_id }}"
device_name: "/dev/sdb"
loop: "{{ ec2_facts.instances }}"
loop_control:
loop_var: instance