How to create an Image using AWS Codepipeline with EC2 Image Builder

0

Is this steps necessary to have immutable servers

  1. Source Stage:

    • Connects to your GitHub repository using AWS CodeCommit.
    • Pulls the latest code to start the pipeline.
  2. Build Stage:

    • Uses AWS CodeBuild to build the Docker image.
    • Pushes the Docker image to Amazon ECR.
  3. Build AMI Stage:

    • Uses AWS CloudFormation to create an EC2 Image Builder pipeline.
    • Builds an AMI with the latest Docker image.
  4. Rollout Stage:

    • Uses AWS CloudFormation to deploy the AMI to EC2 instances.
    • Utilizes Auto Scaling for a rolling update of the instances.

This setup ensures a complete CI/CD pipeline that automates building, AMI creation, and deployment of your application using AWS services.

1 Answer
1

Hi code2go,

Please go through the below steps try it once it will be helpful to complete your query.

1.Source Stage

Set up AWS CodePipeline:

  • Navigate to the AWS CodePipeline console.
  • Create a new pipeline and configure the source stage to connect to your GitHub repository.
  • Use a personal access token from GitHub for authentication.
  1. Build Stage

AWS CodeBuild Project:

Define a buildspec.yml file in your repository:

version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account_id>.dkr.ecr.<region>.amazonaws.com
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t <image_name> .
      - docker tag <image_name>:latest <account_id>.dkr.ecr.<region>.amazonaws.com/<image_name>:latest
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker image...
      - docker push <account_id>.dkr.ecr.<region>.amazonaws.com/<image_name>:latest

  • Configure CodeBuild Project:

  • Create a CodeBuild project in the AWS console.

  • Set the source to your GitHub repository.

  • Use the provided buildspec.yml file.

  • Configure an IAM role with the necessary permissions for CodeBuild to interact with ECR.

  1. Build AMI Stage

AWS CloudFormation Template:

Define a CloudFormation template for EC2 Image Builder:

Resources:
  ImagePipeline:
    Type: AWS::ImageBuilder::ImagePipeline
    Properties:
      ImagePipelineName: my-image-pipeline
      ImageRecipeArn: !Ref ImageRecipe
      InfrastructureConfigurationArn: !Ref InfrastructureConfiguration

  ImageRecipe:
    Type: AWS::ImageBuilder::ImageRecipe
    Properties:
      Name: my-recipe
      Version: 1.0.0
      Components:
        - ComponentArn: arn:aws:imagebuilder:<region>:aws:component/docker/<version>
      ParentImage: arn:aws:imagebuilder:<region>:aws:image/amazon-linux-2-x86/x.x.x
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeSize: 30
            VolumeType: gp2

  InfrastructureConfiguration:
    Type: AWS::ImageBuilder::InfrastructureConfiguration
    Properties:
      Name: my-infrastructure-configuration
      InstanceTypes:
        - t3.medium
      SecurityGroupIds:
        - sg-xxxxxxxx
      SubnetId: subnet-xxxxxxxx
      Logging:
        S3Logs:
          S3BucketName: my-log-bucket

Deploy CloudFormation Template:

Deploy the CloudFormation template to create the EC2 Image Builder pipeline.

  1. Rollout Stage

AWS CloudFormation Template for Deployment:

Define a CloudFormation template for creating an Auto Scaling Group:

Resources:
  AutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: my-asg
      LaunchConfigurationName: !Ref LaunchConfiguration
      MinSize: 1
      MaxSize: 3
      DesiredCapacity: 1
      VPCZoneIdentifier:
        - subnet-xxxxxxxx
      Tags:
        - Key: Name
          Value: MyInstance
          PropagateAtLaunch: true
      HealthCheckType: EC2
      HealthCheckGracePeriod: 300
      UpdatePolicy:
        AutoScalingRollingUpdate:
          MinInstancesInService: 1
          MaxBatchSize: 1
          PauseTime: PT0S
          WaitOnResourceSignals: true

  LaunchConfiguration:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      ImageId: ami-xxxxxxxx  # Replace with the AMI ID from the Image Builder pipeline
      InstanceType: t3.medium
      SecurityGroups:
        - sg-xxxxxxxx
      IamInstanceProfile: !Ref InstanceProfile
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          docker run -d <account_id>.dkr.ecr.<region>.amazonaws.com/<image_name>:latest

  InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref InstanceRole

  InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: my-policy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - ecr:GetDownloadUrlForLayer
                  - ecr:BatchGetImage
                  - ecr:GetAuthorizationToken
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'

Deploy the CloudFormation Template: Deploy the CloudFormation template to create the Auto Scaling Group and other necessary resources.

EXPERT
answered a month ago
profile picture
EXPERT
reviewed 20 days ago
profile pictureAWS
EXPERT
reviewed a month ago
  • What is the use of the Image stored in ECR? how can i access my app right then? thankyou!

  • The Docker image in Amazon ECR is used to package your application and its dependencies, ensuring consistency across different environments (development, testing, production).

    Steps to Access Your Application

    Deploy the Docker Image on EC2 Instances:

    1. Launch EC2 instances using an AMI that includes your Docker image.
    2. Use a startup script to pull and run the Docker image from ECR on the instance.

    Access the Application: 1. Direct Access: Use the public IP of the EC2 instance http://<ec2-instance-public-ip>

     2. Load Balancer: Use an Elastic Load Balancer (ELB) to distribute traffic
          http://<load-balancer-dns-name>
    
  • Hi, does the EC2 Image builder will create instance? Could you please explain what is the flow if I have an image in the ecr and what will be its connection for EC2 image builder. Thank you so much