how to take all ebs snapshots of ec2 with specific tags with Ansible?

36 Views Asked by At

I have an ansible role to take snapshots of all ebs volume (/dev/sdb) attached to ec2 instances with backup tag.

- 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"

The script works fine, but when there are multiple instances within the same tags, it only takes snapshot for the first one. Is there any way to take snapshots for every volume of instances within those tags?

1

There are 1 best solutions below

0
Alexander Pletnev On

Sure, you just need to iterate over the list instead of using the first instance:

- 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

It is not a role, by the way, but a playbook. To simplify the code, you can set the module parameters that repeat for all module invocations to module_defaults. It also makes sense to parametrize the device name since it can differ from /dev/sdb:

- name: "take snapshots of vms with backup:yes tag"
  hosts: localhost
  module_defaults:
    group/aws:
      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: "{{ ebs_device_name | default('/dev/sdb') }}"
    loop: "{{ ec2_facts.instances }}"
    loop_control:
      loop_var: instance