Quick guide to start using AWS CodeCommit via AWS CLI
Tags: aws, git, cloud, awscodecommit
Published: 2020-12-28 01:41:35

I was looking for AWS CodeCommit quick tutorial and ended up watching ACloudGuru’s [“Manage and Deploy Code with AWS Developer Tools”] (https://acloud.guru/overview/7f9e16d6-414d-42fd-ad70-970a24f49c2b?_ga=2.245456836.1979153929.1608879327-652555336.1598814393&_gac=1.123506169.1607550672.CjwKCAiAiML-BRAAEiwAuWVggoVc8w3OZdP0p1SSyEJcIFYXPwO6_ZNyST0_B2Zp07x30rTC6N0ljRoCA-UQAvD_BwE) 8 hour course (BTW, a great one!), reading some articles and AWS documentations. Based on that I’ve decided to create a quick guide to start using AWS CodeCommit via AWS CLI.

## **What is AWS CodeCommit?**

Think of it as an AWS version of GitHub. In other words, AWS CodeCommit is a managed source control service that hosts private Git repositories. You can use CodeCommit to store and manage documents, source code, and binary files in the cloud.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qenl5peplc4h7im3ixrl.jpg)

CodeCommit is integrated with a number of AWS services such as  CodeBuild, CodePipeline, Lambda, SNS, Amplify, CloudFormation, etc.

## **AWS CodeCommit vs GitHub**

Both can be primarily classified as "Code Collaboration & Version Control" tools. 

| Similarities |
| ----------- |
| Support code review |
| Use two methods of authentication, SSH and HTTPS |
| Use Git repositories|

Based on comparison [provided by CompareCamp](https://comparecamp.com/aws-codecommit-vs-github-comparison/), here are some cons and pros of both services:

| AWS CodeCommit Pros | AWS CodeCommit Cons |
| ------------------- | ------------------- |
| free private repos (for up to 5 users) | complex menu options|
| faster deployments using AWS solutions | resubmit flow and code review unavailable |
| encrypted repo data | limited triggers |
| issue tracker | lack of CI system integrations |

On the other hand,

| GitHub Pros | GitHub  Cons |
| ----------- | ------------ |
| ease of use | notifications are hard to configure |
| easy integration with third-party tools | lack of first-party support for mobile |
| code highlighting for ObjectScript| lack of command-line configuration options |
| comprehensive issue tracking | security scanning problems|

## **Prerequisites and setup (using HTTPS)**

Of course, you can use AWS CodeCommit console with friendly UI to manage files and repositories directly. But in order  to work with multiple files, files across branches, and also to control multiple AWS services from the command line and automate them through scripts consider setting up your local computer to work with AWS CodeCommit via AWS CLI.

#### Step 1. Install [**Git**](https://git-scm.com/)
Check installation by running the following command:
```YAML
git --version
```

#### Step 2. Install [**AWS CLI**](https://aws.amazon.com/cli/)
Check installation by running the following command:
```YAML
aws --version
```

#### Step 3. Create Git credentials for IAM user

Firstly, create a new AWS IAM user and give it a **Programmatic access**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mx7qgo7tp6r0modwmeaz.png)

Then attach **AWSCodeCommitFullAccess** policy to the user.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rcmptsuga4j5ui2t8frn.png)

Store a user's credentials in a safe place

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/atn0q86kzyuheizw11jx.png)


#### Step 4. Configure [**AWS CLI**](https://aws.amazon.com/cli/)

Use the following command and enter newly created **Access key ID** and **Secret access key**:
```YAML
aws configure
```

AWS CLI will also ask you to enter the **Region** whose servers you want to send your requests to. By default it is typically the region closest to you, but you can enter any other region.

And finally, you might want to specify **Output format** how the results are formatted. *json* is used as the default, but you can use *yaml*, *yaml-stream* (streaming allows for faster handling of large data types), *text*, and *table* formats.

Alternatively, you can set up AWS CodeCommit using **SSH connections** for [Windows](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-windows.html) and for [Linux, macOS, or Unix](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-unixes.html).

## **Pricing**

| First 5 active users | Each additional active user beyond the first 5|
| ----------- | ----------- |
| $0.00       | $1.00 per month |
|Unlimited repositories|Unlimited repositories|
|50 GB-month of storage|10 GB-month of storage per active user|
|10,000 Git requests/month|2,000 Git requests/month per active user|

Check the latest prices [here](https://aws.amazon.com/codecommit/pricing/).

## **AWS CodeCommit commands**

[Here](https://docs.aws.amazon.com/cli/latest/reference/codecommit/index.html) is a full list of AWS CodeCommit commands. In this article, we are going to understand how to use the top command. Just follow along the guide to get a basic experience with AWS CodeCommit.

* To **create a new repository**, run:
```YAML
aws codecommit create-repository --repository-name MyDemoRepo --repository-description "This is a demo repo"
```

Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8b9qjf1ctpzkkhb0wz5s.png)

You should find a new repo on AWS CodeCommit Console:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rmr5deyas00mh3fm9cp1.png)



* To **get a list of all existing repositories**, run:
```YAML
aws codecommit list-repositories
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q72prug5hh0xqldm4v17.png)


* To **get information about specific repository**, run:
```YAML
aws codecommit get-repository --repository-name MyDemoRepo
```


* To **get information about multiple specific repositories**, run:
```YAML
aws codecommit batch-get-repositories --repository-names MyDemoRepo MyBestRepo
```


* To **update repository’s name**, run:
```YAML
aws codecommit update-repository-name --old-name MyDemoRepo --new-name MyDemo2Repo
```


* To **update repository’s description**, run:
```YAML
aws codecommit update-repository-description --repository-name  MyDemo2Repo --repository-description "This is updated description"
```


* To **clone repository**, you need to get a url from AWS CodeCommit console 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0ndxskitzh0kwz4xxgfz.png)

then run the following commands:
```YAML
# navigate to your local directory
cd "C:\Users\{userName}\{folder}\{nested-folder}"
# # clone a repository from AWS CodeCommit to your local machine
git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemo2Repo localMyDemo2Repo
```
Important! If a Windows Security is popped up asking for username and password, then **cancel it**
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m3bgo0i3tfnhz1dxtabs.png)

In my case I still got the warning about an empty repository with a **successfully** copied repository on my local machine.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rd1nj1x4kpgu7pfuwubt.png)

The issue has gone once I've uninstalled and reinstalled Git for Windows with **cleared the check box for the option to install the Git Credential Manager utility** ([details](https://docs.aws.amazon.com/codecommit/latest/userguide/troubleshooting-ch.html#troubleshooting-windowshttps)) because the credential manager is not compatible with the credential helper for AWS CodeCommit.

If you got  different kind of issues while attempting to clone a repository, see AWS's [Troubleshooting section](https://docs.aws.amazon.com/codecommit/latest/userguide/troubleshooting.html).

* To **commit and push changes to AWS CodeCommit**, run Git commands:
```YAML
# navigate to your local repository
cd localMyDemo2Repo
# create a sample text file
echo "Greeting, AWS CodeCommit nerds! Let's rock it!" > hello.txt
# stage the file for commit to your local repository
git add .
# commit the file that you've staged
git commit -m"Add a new hello file"
# push the changes in your local repository to AWS CodeCommit
git push origin master
```
As a result, a new "hello.txt" file should be added to remote repository:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zmxvb97n8cprse575hd2.png)

To manage branches, merges, tags, logs, etc, use *Git* commands. You can find the full list of Git commands [here](https://git-scm.com/docs) and one of my favorite Git cheat sheet [here](https://about.gitlab.com/images/press/git-cheat-sheet.pdf). 

* To **view information about current repository**, run:
```YAML
git remote show origin
```
Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/msnam5bg8v74srkv4u7i.png)

Also, it you want to know how to migrating a repository from GitHub into AWS CodeCommit via AWS CLI, check [this](https://dev.to/tiamatt/migrating-a-repository-from-github-into-aws-codecommit-via-aws-cli-2ne4) article.

## **Create AWS CodeCommit trigger to send notification via Amazon SNS**

You can configure a AWS CodeCommit repository so that code pushes or other events trigger notification from Amazon SNS. Beware of limitations, as AWS allows up to 10 triggers for each CodeCommit repository.

Let's configure "MyDemo2Repo" repository in AWS CodeCommit so that any event triggers Amazon SNS to send a notification to email.

#### Step 1. Give an IAM user some permissions to manage Amazon SNS

An IAM user named 'code-commit-user' doesn't have enough permissions to manage an Amazon SNS. In addition to AWSCodeCommitFullAccess policy you might want to attach **AmazonSNSFullAccess** policy to that user:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/blk6xy35gy6icqvyuccl.png)

#### Step 2. Create an SNS topic

To create a topic, use the *aws sns create-topic* command and specify the name to assign to the topic:

```YAML
aws sns create-topic --name my-codecommit-trigger
```

You should get a *TopicArn* as a response - write it down for step 3:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x21kcobxqpyndh17vppe.png)

#### Step 3. Subscribe to a topic

Create a subscription and subscribe to a topic specifying *TopicArn*:

```YAML
aws sns subscribe --topic-arn arn:aws:sns:{your-region}:{your-accountId}:my-codecommit-trigger --protocol email --notification-endpoint {your-email@blah.blah}
```
Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3vz82icsoi6q7cy3eyun.png)

AWS immediately sends a confirmation message by email to your address. You need to confirm the subscription.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uy7n8xkn188jroffeloz.png)

Once confirmed, your browser should display a notification message with information similar to the following:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1snzugzuiicdpfo1o09h.png)

You can find a newly created topic on Amazon SNS Console:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4nkhlnjtgpxwbgdyw7f5.png)

#### Step 4. Create a JSON file with trigger description

Next step is to create a trigger for a CodeCommit repository so that events in that repository trigger notifications from SNS topic. 

Firstly, create a JSON file that specifies SNS topic name, the repository and branches you want to monitor with this trigger, and the events that activate this trigger.

For example, to create a trigger for a repository named *MyDemo2Repo* that publishes *all* repository events to an Amazon SNS topic named *my-codecommit-trigger* for a *master* branch, save the following code in 'my-first-codecommit-trigger.json' file:

```YAML
{
    "repositoryName": "MyDemo2Repo",
    "triggers": [
        {
            "name": "AllEventsTriggerForMyDemo2Repo",
            "destinationArn": "arn:aws:sns:{your-region}:{your-accountId}:my-codecommit-trigger",
            "customData": "",
            "branches": [
                "master"
            ],
            "events": [
                "all"
            ]
        }
    ]
}
```

In our example we used **all** event type but here is the full list of event types you can create triggers for:

| Event       | Description |
| ----------- | ----------- |
| all | for all events in the specified repository and branches |
| updateReference | for when commits are pushed to the specified repository and branches |
| createReference | for when a new branch or tag is created in the specified repository |
| deleteReference | for when a branch or tag is deleted in the specified repository |


Let's test our json file:
```YAML
 aws codecommit test-repository-triggers --cli-input-json "file://C:\Users\{your-folders}\my-first-codecommit-trigger.json"
```
Note, you have to use **file://** before the json name.

If successful, this command returns information similar to the following:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xvmsl3meaxyal56uyc8j.png)

#### Step 5. Create a trigger

Now it's time to create a trigger in AWS CodeCommit that is described in json file. The command is similar to the previous one but instead of *'test'* use *'put'*:

```YAML
 aws codecommit put-repository-triggers --cli-input-json "file://C:\Users\{your-folders}\my-first-codecommit-trigger.json"
```

This command returns a configuration ID:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ign9dhoz1rjoo4uleojl.png)

Check your email, you should get a very first notification from AWS:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q8lm3lw04k701mmw62c6.png)

#### Step 6. View trigger configuration 

If you want to view the configuration of the trigger for target repository, run:

```YAML
aws codecommit get-repository-triggers --repository-name MyDemo2Repo
```

Output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dxzll4d3fdy8whdj79l6.png)

#### Step 7. Make some repository changes

To test the functionality of the trigger itself, make and push a commit to the repository where you configured the trigger. You should see a response from the Amazon SNS topic. 

```YAML
# navigate to your local repository
cd localMyDemo2Repo
# create a text file
echo "This is a new file for MyDemo2Repo repository that should trigger a notification from AWS SNS topic" > test-sns.txt
# stage the file for commit to your local repository
git add .
# commit the file that you've staged
git commit -m"Add a new test-sns file"
# push the changes in your local repository to AWS CodeCommit
git push origin master
```

As a result, a new "test-sns.txt" file should be added to remote repository and a new notification from AWS should be sent to your email:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m2d4of2xgmieid5si0az.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0pc2q3xbpfwoeunoxoa2.png)

## **Clean up**

To avoid ongoing charges for resources you created to complete this guide, let's delete our repository and sns topic:

```YAML
# get the list of all subscriptions
aws sns list-subscriptions
# from the list above get a target SubscriptionArn and use it in command below to unsubscribe from a topic and stop receiving messages published to that topic
aws sns unsubscribe --subscription-arn {your-SubscriptionArn }
# get the list of all sns topics
aws sns list-topics
# from the list above get a target TopicArn and use it in command below to delete SNS topic
aws sns delete-topic --topic-arn {your-TopicArn}
# get the list of all repositories
aws codecommit list-repositories
# from the list above get a target repositoryName and use it in command below to delete repository 
aws codecommit delete-repository --repository-name MyDemo2Repo
```
All done! Till the next time.