Using CloudFormation to bootstrap EC2 instances with scripts from CodeCommit

26 Aug

While spinning up EC2 instances you can bootstrap them with packages, files, etc in different ways. For our stack we wanted to pull scripts from an AWS CodeCommit to make life easier.

The (bash) scripts are stored in our CodeCommit so first we need to make sure the EC2 instances, while spinning up, are allowed to access the repository. So we created an IAM Policy with these sufficient rights and attach the policy to a IAM role which we can use to attach to our EC2 instances.

AWS IAM Policy:

    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": [
            "Resource": "arn:aws:codecommit:*:*:terra10-scripts"
            "Effect": "Allow",
            "Action": [
            "Resource": "*"

We make sure the EC2 instances uses the new IAM Role by defining IamInstanceProfile with our example IAM Role t10-ec2-role in the CloudFormation template. Further on by using the UserData segment we can execute scripts during bootstrap of the server. Install the AWSCLI is required for the credential helper

  Type: AWS::EC2::Instance
    ImageId: !Ref HostAMI
    InstanceType: t2.micro
    IamInstanceProfile: t10-ec2-role
      - Key: Name
        Value: t10-k8s-controller1
      Fn::Base64: !Sub |
        #!bin/bash -xe
        apt-get update
        apt-get -y install awscli
        cd /tmp
        echo "######## git pull AWS CodeCommit files"
        sudo git config --global credential.helper '!aws codecommit credential-helper $@'
        sudo git config --global credential.UseHttpPath true
        sudo git clone /tmp/terra10-scripts


Leave a comment

Posted by on 26-08-2018 in AWS


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: