How to dynamically tag an AMI created by an EC2 Image Builder

438 Views Asked by At

I have an EC2 Image Builder which is triggered when an new version of a package is pushed to CodeArtifact. I would like to tag the resulting AMI with the version of the package that triggered the build. My goal is to add a tag that is meaningful to us than the unique build number created by the pipeline.

I see in the distribution settings how to set a tag with a constant value for the AMI. I don't see a way to update that value based on what triggered the the creation of the image in the first place.

2

There are 2 best solutions below

0
On BEST ANSWER

I solved this same problem by adding a test component to the Image Build Pipeline that runs the following commands to tag the AMI during the testing phase. It wont work during the Build phases since the AMI is not created until the end of the build process so it has to the be ran in the testing phase.

phases:
  - name: test
    steps:
      - name: tag-ami
        action: ExecuteBash
        inputs:
          commands:
            - sudo yum install jq -y
            - cd /tmp
            - aws codeartifact list-package-versions --region <Region> --domain <Domain> --domain-owner <AWS Owner Account Number> --repository <Repo Name> --format <Format> --namespace <NameSpace> --package <PackageName> >> tagpackage.json
            - export version=$(cat tagpackage.json |jq -r .defaultDisplayVersion)
            - hostname -i > privateip.txt 
            - export privateip=$(cat privateip.txt)
            - instance_json=$(aws ec2 describe-instances --filters Name=private-ip-address,Values=$privateip)
            - export instance_id=$(echo $instance_json | jq -r .Reservations[].Instances[].InstanceId)
            - export imageid=$(aws ec2 describe-instances --instance-ids $instance_id --query 'Reservations[*].Instances[*].[ImageId]' --output text)
            - aws ec2 create-tags --resources $imageid --tags Key=Version,Value=$version
0
On

Faced with similar problem. To tackle it, I have done the following:

  • Store and update my dynamic version value in an SSM parameter.
  • Setup an SNS topic to use against the Image Builder infrastructure configuration.
  • Created a Lambda function with an SNS trigger.
  • The Lambda function will take the content of the Image Builder message to SNS, strip out the data I need, such as AMI ID. Then use Boto3 to get the SSM parameter and apply the tag.