Pankaj Rudrawar
Pankaj Rudrawar

Reputation: 7

Automate latest AMI for EC2 Image Builder or Packer

Want to automate using any Jenkins Pipeline : How to detect the latest AMI ID available and use that for customization like additional packages ?

Any other tool to detect new AMI and deploy EC2 Instance.

Upvotes: -1

Views: 2188

Answers (4)

Brendan
Brendan

Reputation: 1

Adding a more up-to-date answer for those looking like I was:

Imagebuilder now has it's own set of AWS managed AMIs that you can reference with version wildcards.

Upvotes: 0

lokitechie06
lokitechie06

Reputation: 11

Try using EC2 ImageBuilder (if you want to develop a custom AMI with additional packages) which can be later used to deploy EC2Instance.

I have worked on the same using terraform. Here are the resources: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/imagebuilder_component

Assuming either that the custom AMI is built or using base image AMI, use a data lookup element to get the most recent image:

data "aws_ami" "latest_version"{ 
     owners = [#replace with accountID] 
     most_recent=true
     name_regex = "#replace with your AMI name if needed" 
}

Once you add the required data lookup element, while creating the ec2 instance, you can use this AMI-ID, so that you will have the most recent AMI version.

resource "aws_instance" "new_instance"{
    ami = data.aws_ami.new_instance.id
    #....other resource properties...#
}

We can manage the terraform state files using Jenkins.

Upvotes: 1

Aditya Nair
Aditya Nair

Reputation: 582

Try fetching the latest AMI Id of the specified image name from AWS SSM. Search for the required AMI's name in AWS SSM. For example, to fetch the latest AMI details of Windows 2019 server, call this aws cli command:

aws ssm get-parameter --name /aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base

You may automate it using jenkins to fetch the AMI Id by using shell or powershell script and querying json output. You can also use python boto3 library to fetch the ami Id:

import os
import sys,json
import time
import boto3

ssmParameter = str(sys.argv[1])
region = str(sys.argv[2])
client = boto3.client('ssm', region)

response = client.get_parameter(
    Name=ssmParameter
)

amiValue = json.loads(response['Parameter']['Value'])
print(amiValue['image_id'])
    
sys.stdout.flush()    

It can be called as follows to fetch ami id of Windows server 2019:

python filename.py '/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base' 'us-east-1'

Upvotes: 0

albertogg
albertogg

Reputation: 202

There might be other options available, but the one I know is subscribing to the AWS AMI SNS topic, then use AWS EventBridge to send a notification to your system, if you are using CodeBuild, then you could trigger it directly. If you are using Jenkins then you could trigger your Jenkins pipeline via a Webhook or something.

Upvotes: 0

Related Questions