如何使用 Ansible 拍摄带有特定标签的 ec2 的所有 ebs 快照?

问题描述 投票:0回答:1

我有一个 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"

该脚本工作正常,但当同一标签内有多个实例时,它只会拍摄第一个实例的快照。有没有办法为这些标签内的每个实例卷拍摄快照?

amazon-web-services amazon-ec2 ansible yaml amazon-ebs
1个回答
0
投票

当然,您只需要迭代列表而不是使用第一个实例:

- 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
© www.soinside.com 2019 - 2024. All rights reserved.