Sometimes, you might have to fetch your own git repository from an AMI. In order to achieve this, you need a role which allows your EC2 instance to access the git repository. So, in your IAM create a new role with the attached policy AWSCodeCommitReadOnly and a trust relationship for EC2.

You’ll also have to give yourself the permission to pass a role to an EC2 instance.

{
    "Effect": "Allow",
    "Action": "iam:PassRole",
    "Resource": "arn-for-your-repository"
}

When you startup an instance using create_instance you can now pass the Instance Profile ARN to the EC2 instance. Pay attention not to use the Role ARN.

On the current AMI of Ubuntu (Ubuntu Server 14.04, ami-fce3c696) there’s a higher burden. If you want to use CodeCommit from this AMI without setting up SSH keys (i.e. using HTTPS and the credential helper), you’ll receive this nice little error:

error: gnutls_handshake() failed

According to askubuntu, this is a problem with gnutls and can be solved by replacing it with openssl. So, you’ll have to do this first. We can automatize the steps from the answer into our startup script:

apt-get -y install build-essential fakeroot dpkg-dev  
mkdir /root/git-openssl
cd /root/git-openssl 
apt-get source git
apt-get -y build-dep git  
apt-get -y install libcurl4-openssl-dev  
dpkg-source -x git_*.dsc                 
cd git-*                
sed -i s/libcurl4-gnutls-dev/libcurl4-openssl-dev/g debian/control
sed -i "s/TEST =test//g" debian/rules                             
dpkg-buildpackage -rfakeroot -b      
dpkg -i ../git_*_amd64.deb

After this step you have to setup the credential helper for git:

cd $HOME
echo "[credential]" > .gitconfig
echo "helper = !aws codecommit credential-helper $@" >> .gitconfig
echo "UseHttpPath = true" >> .gitconfig
git clone $HTTPS_REPO_URL

The Ubuntu AMI does not include the awscli and the one in the Ubuntu repository is outdated and does not include codecommit commands. So, you should install awscli from pip.

apt-get install -y python-pip
pip install awscli

Now you are ready to clone your git repository:

git clone $HTTPS_REPO_URL
I do not maintain a comments section. If you have any questions or comments regarding my posts, please do not hesitate to send me an e-mail to stefan@eliteinformatiker.de.