> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ahmadraza.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Auto ami creation

To implement automatic creation of Amazon Machine Images (AMIs) and deletion of old images for your EC2 instances, you can use AWS services and scripting. Here’s a step-by-step guide to achieve this:

### **1. Automate AMI Creation**

**Using AWS Systems Manager Automation:**

1. **Create an Automation Document:**
   * Go to the **AWS Systems Manager** console.
   * Navigate to **Automation** under **Systems Manager**.
   * Click **Create Document** and select **AWS-CreateImage** document or create a custom document.
   * Configure the document to create AMIs for your EC2 instances.

2. **Define Parameters:**
   * Set parameters for the instance ID and AMI name.
   * For example:
     ```json theme={null}
     {
       "instanceId": {
         "type": "String",
         "description": "The ID of the instance to create an AMI from."
       },
       "imageName": {
         "type": "String",
         "description": "The name of the AMI to create."
       }
     }
     ```

3. **Create an Automation Execution:**
   * Go to the **Automation** tab in the **Systems Manager** console.
   * Click **Execute automation** and select the document you created.
   * Provide necessary parameters and schedule the automation to run periodically (e.g., daily, weekly).

**Using AWS Lambda and CloudWatch Events:**

1. **Create a Lambda Function:**
   * Go to the **Lambda** console and create a new Lambda function.
   * Use the following Python code as an example to create AMIs:

     ```python theme={null}
     import boto3
     from datetime import datetime

     ec2 = boto3.client('ec2')

     def lambda_handler(event, context):
         instance_id = 'i-0123456789abcdef0'  # Replace with your instance ID
         image_name = f"ami-{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
         
         response = ec2.create_image(
             InstanceId=instance_id,
             Name=image_name,
             NoReboot=True
         )
         
         return {
             'statusCode': 200,
             'body': response
         }
     ```

2. **Schedule Lambda Execution:**
   * Use **Amazon CloudWatch Events** to trigger the Lambda function at regular intervals.
   * Create a rule in CloudWatch Events to schedule the Lambda function (e.g., daily).

### **2. Automate Deletion of Old AMIs**

**Using AWS Lambda and CloudWatch Events:**

1. **Create a Lambda Function for AMI Cleanup:**
   * Go to the **Lambda** console and create another Lambda function.
   * Use the following Python code as an example to delete old AMIs:

     ```python theme={null}
     import boto3
     from datetime import datetime, timedelta

     ec2 = boto3.client('ec2')

     def lambda_handler(event, context):
         # Define how old an AMI should be before it is deleted
         days_old = 30
         cutoff_date = datetime.now() - timedelta(days=days_old)

         # List AMIs
         response = ec2.describe_images(Owners=['self'])
         images = response['Images']
         
         for image in images:
             creation_date = image['CreationDate']
             creation_date = datetime.strptime(creation_date, '%Y-%m-%dT%H:%M:%S.%fZ')
             
             if creation_date < cutoff_date:
                 image_id = image['ImageId']
                 print(f'Deleting AMI {image_id} created on {creation_date}')
                 
                 # Deregister AMI
                 ec2.deregister_image(ImageId=image_id)
                 
                 # Delete associated snapshots (optional)
                 for snapshot_id in image['BlockDeviceMappings']:
                     ec2.delete_snapshot(SnapshotId=snapshot_id['Ebs']['SnapshotId'])
         
         return {
             'statusCode': 200,
             'body': 'Old AMIs cleaned up'
         }
     ```

2. **Schedule Lambda Execution:**
   * Use **Amazon CloudWatch Events** to schedule this Lambda function to run at regular intervals (e.g., weekly).

### **3. Verify and Monitor**

* **CloudWatch Logs:** Check the logs of your Lambda functions in CloudWatch Logs to ensure they are running correctly.
* **EC2 Console:** Verify that AMIs are being created and deleted as expected.

### **Summary**

* **Automate AMI Creation:** Use AWS Systems Manager Automation or Lambda functions triggered by CloudWatch Events to create AMIs regularly.
* **Automate AMI Deletion:** Use Lambda functions to clean up old AMIs and optionally delete associated snapshots, scheduled via CloudWatch Events.

This approach ensures that your AMI creation and cleanup process is automated and managed efficiently.

\#AWS #EC2 #AMI #Automation #Lambda #CloudWatch #SystemsManager #CloudComputing #InfrastructureManagement #TechSolutions #ServerManagement #AWSManagement #AMIManagement #AWSAutomation
