Skip to content

Adding-ami-cleanup-role #1580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions roles/aws/aws_ami_asg_cleanup/defaults/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
aws_ami_asg_cleanup:
memory_size: 128 # Memory allocation for Lambda function in MB
timeout: 30 # Time in seconds, max is 900
handler: "clean_up_ami.lambda_handler" # Change this only if the main_file.main_function name is changed
runtime: "python3.12" # If the python version changes we need to update this as well
keep_backups: 10
scheduler_cron: "cron(0 16 ? * SUN *)"
55 changes: 55 additions & 0 deletions roles/aws/aws_ami_asg_cleanup/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
- name: Create a role and attach policies
amazon.aws.iam_role:
name: LambdaAsgAmiCleanupRole
assume_role_policy_document: "{{ lookup('file', 'assume_lambda_iam_policy.j2') }}"
managed_policies:
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
- arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
register: _created_iam_lambda_cleanup_role

- name: Ensure python script is removed
ansible.builtin.file:
path: "{{ _ce_provision_build_dir }}/clean_up_ami.py"
state: absent

- name: Ensure zip file is removed
ansible.builtin.file:
path: "{{ _ce_provision_build_dir }}/clean_up_ami.zip"
state: absent

- name: Write Lambda function
ansible.builtin.template:
src: cleanup_ami.py.j2
dest: "{{ _ce_provision_build_dir }}/clean_up_ami.py"

- name: Create a zip archive of cleanup_ami.py
community.general.archive:
path: "{{ _ce_provision_build_dir }}/clean_up_ami.py"
dest: "{{ _ce_provision_build_dir }}/clean_up_ami.zip"
format: zip

- name: Create Lambda function
amazon.aws.lambda:
name: "clean_up_ami"
region: "{{ _aws_region }}"
timeout: "{{ aws_ami_asg_cleanup.timeout }}"
state: present
zip_file: "{{ _ce_provision_build_dir }}/clean_up_ami.zip"
runtime: "{{ aws_ami_asg_cleanup.runtime }}"
role: "{{ _created_iam_lambda_cleanup_role.iam_role.arn }}"
handler: '{{ aws_ami_asg_cleanup.handler }}'
tags:
Test: 'This is test tag'
register: _created_iam_lambda_cleanup_function

- name: Create scheduler to invoke Lambda function
amazon.aws.cloudwatchevent_rule:
name: cleanup_asg_ami
schedule_expression: "{{ aws_ami_asg_cleanup.scheduler_cron }}"
description: Clean up ASG AMIs
region: "{{ _aws_region }}"
targets:
- id: 'clean_up_ami'
arn: "{{ _created_iam_lambda_cleanup_function.configuration.function_arn }}"
input: '{"asg_name": "{{ _domain_name | regex_replace("\.", "-") }}"}'
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
27 changes: 27 additions & 0 deletions roles/aws/aws_ami_asg_cleanup/templates/cleanup_ami.py.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import json
import boto3

def lambda_handler(event, context):
ec2 = boto3.client("ec2", "{{ _aws_region }}")

images = ec2.describe_images(
Filters=[
{
'Name': 'tag:Name',
'Values': [
event['asg_name'] + '*'
]
}
]
)

# Order AMIs by CreationDate
ordered_images = sorted(images['Images'], key=lambda d: d['CreationDate'])

# Remove latest 10 AMIs from list
ordered_images = ordered_images[:len(ordered_images)-{{ aws_ami_asg_cleanup.keep_backups }}]

for x in ordered_images:
ec2.deregister_image(ImageId=x['ImageId'])

print(len(ordered_images))
4 changes: 4 additions & 0 deletions roles/aws/aws_ec2_autoscale_cluster/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,10 @@
- aws_ec2_autoscale_cluster.type == "ec2"
- aws_ec2_autoscale_cluster.deploy_cluster

- name: Create ami cleanup function
ansible.builtin.include_role:
name: aws/aws_ami_asg_cleanup

- name: Gather IAM role info.
amazon.aws.iam_role_info:
profile: "{{ aws_ec2_autoscale_cluster.aws_profile }}"
Expand Down
Loading