How do I perform Git operations on an AWS CodeCommit repository with an instance role on Amazon EC2 instances for Amazon Linux 2?

Last updated: 2020-10-20

I want to perform Git operations on an AWS CodeCommit repository with an instance role on Amazon Elastic Compute Cloud (Amazon EC2) instances for Amazon Linux 2.

Short description

You can use the AWS Command Line Interface (AWS CLI) credential helper to perform Git operations on a CodeCommit repository using an AWS Identity and Access Management (IAM) role on your EC2 instance.

Note: Using a credential helper is the only connection method for CodeCommit repositories that doesn't require an IAM user.

Resolution

Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.

1.    Create an IAM role for your EC2 instance, and then attach the following example IAM policy to the role. Replace arn:aws:codecommit:us-east-1:111111111111:testrepo with the ARN of your CodeCommit repository.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
       
            "codecommit:GitPull",
                "codecommit:GitPush"
            ],
            "Resource": "arn:aws:codecommit:us-east-1:111111111111:testrepo"
 
          }
    ]
}

Note: The policy for step 1 allows the IAM role to perform Git pull and push actions on the CodeCommit repository. For more examples on using IAM policies for CodeCommit, see Using identity-based policies (IAM Policies) for CodeCommit.

2.    Attach the IAM role that you created in step 1 to an EC2 instance.

3.    Install Git on your EC2 instance.

Note: For more information, see Downloads on the Git website.

4.    To set up the credential helper on the EC2 instance, run the following commands:

$ git config --global credential.helper '!aws codecommit credential-helper $@'
$ git config --global credential.UseHttpPath true

Note: The commands in step 4 specify the use of the Git credential helper with the AWS credential profile. The credential profile enables Git to use HTTPS and a cryptographically signed version of your EC2 instance role whenever Git needs to authenticate with AWS to interact with CodeCommit repositories.

5.    To configure your name and email address explicitly, run the following command:

$ git config --global user.email "testuser@example.com"
$ git config --global user.name "testuser"

Note: Your name and email address are configured automatically based on your user name and hostname.

6.    To clone the repository to the EC2 instance, run the following command:

$ git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/testrepo