86 lines
2.4 KiB
YAML
86 lines
2.4 KiB
YAML
|
- name: Remove the oldest AMI and associated snapshots
|
||
|
hosts: localhost
|
||
|
connection: local
|
||
|
gather_facts: True
|
||
|
|
||
|
vars:
|
||
|
enable_debug: False
|
||
|
aws_profile: aws-ansible
|
||
|
log_destination: /tmp/ansible-ami-cleanup.log
|
||
|
ami_tag:
|
||
|
"tag:DestroyImage": 'true'
|
||
|
|
||
|
tasks:
|
||
|
- name: Register the AWS_REGION environment variable.
|
||
|
set_fact:
|
||
|
aws_region_env_var: "{{ lookup('env', 'AWS_REGION') }}"
|
||
|
register: aws_region_env_var
|
||
|
|
||
|
- name: Fail if the AWs_REGION environemtn var is not set
|
||
|
fail:
|
||
|
msg: "The AWS_REGION environment variable is not set"
|
||
|
when: not aws_region_env_var
|
||
|
|
||
|
- name: Gather facts about all AMIs with given tag.
|
||
|
ec2_ami_facts:
|
||
|
profile: "{{ aws_profile }}"
|
||
|
owners: self
|
||
|
filters: "{{ ami_tag }}"
|
||
|
register: ami_list
|
||
|
|
||
|
- name: Check if log file already exists
|
||
|
stat:
|
||
|
path: "{{ log_destination }}"
|
||
|
register: logfile
|
||
|
|
||
|
- name: Create log file
|
||
|
file:
|
||
|
state: touch
|
||
|
path: "{{ log_destination }}"
|
||
|
when: logfile.stat.exists == False
|
||
|
|
||
|
- name: debug
|
||
|
debug:
|
||
|
msg: "{{ ami_list }}"
|
||
|
when: enable_debug
|
||
|
|
||
|
- name: oldest ami
|
||
|
set_fact:
|
||
|
oldest_ami: "{{ ami_list.images | sort(attribute='creation_date') | first}}"
|
||
|
when: ami_list.images
|
||
|
|
||
|
- name: debug
|
||
|
debug:
|
||
|
msg: "{{ oldest_ami }}"
|
||
|
when: enable_debug and ami_list.images
|
||
|
|
||
|
- name: Deregister AMI.
|
||
|
ec2_ami:
|
||
|
profile: "{{ aws_profile }}"
|
||
|
image_id: "{{ oldest_ami.image_id }}"
|
||
|
state: absent
|
||
|
# Bug in deleting snapshots : https://github.com/ansible/ansible/issues/39541
|
||
|
#delete_snapshot: yes
|
||
|
when: ami_list.images
|
||
|
|
||
|
- name: LOG action
|
||
|
lineinfile:
|
||
|
line: "{{ ansible_date_time.iso8601 }} AMI CLEANUP - Deregistered AMI: {{ oldest_ami.image_id }}"
|
||
|
dest: "{{ log_destination }}"
|
||
|
when: ami_list.images
|
||
|
|
||
|
- name: Cleanup AMI snapshots
|
||
|
ec2_snapshot:
|
||
|
profile: "{{ aws_profile }}"
|
||
|
snapshot_id: "{{ item.ebs.snapshot_id }}"
|
||
|
state: absent
|
||
|
with_items: "{{ oldest_ami.block_device_mappings }}"
|
||
|
when: ami_list.images
|
||
|
|
||
|
- name: LOG action
|
||
|
lineinfile:
|
||
|
line: "{{ ansible_date_time.iso8601 }} AMI CLEANUP - Removed snapshots: {{ item.ebs.snapshot_id }}"
|
||
|
dest: "{{ log_destination }}"
|
||
|
with_items: "{{ oldest_ami.block_device_mappings }}"
|
||
|
when: ami_list.images
|