Transferring CodeCommit Repositories Between Regions

Recently, the CodeCommit service from AWS became available in Canada (ca-central-1 region). As I'm Canadian, I like to keep my hosting as close to home as possible, for myriad reasons, but mainly because each commit getting appended with "eh!".

The CodeCommit service from Amazon (AWS) hosts Git repositories. That's about it. It's no Github or Gitlab, but it does ensure at-rest encryption and access is limited to specific IAM users. If you just need private Git hosting for free (or on the cheap) without any WebUI help, CodeCommit is good.

So, my repositories were only hosted in the Virginia region (us-east-1) and I needed a way to easily move the repositories to Canada. While this type of task will never happen very often, it does highlight the benefit of automation.

First, create the CloudFormation stacks that hold the CodeCommit repositories. You have CloudFormation stacks creating your CodeCommit resources, right? Great. Then just change the region from us-east-1 to ca-central-1 and relaunch. Now would be a good time to invest in orchestration, may I suggest Ansible?

Now that the infrastructure has been created, don't forget to output the SSH url of the CodeCommit repository.

SSH_URL=$(aws cloudformation describe-stacks --stack-name $NAME --region ca-central-1 --query 'Stacks[].Outputs[].OutputValue' | grep '^ssh://')

Second, create a new Git remote for each repository and push all branches to it. Call this remote canada because origin is already taken. This is as simple as

cd repo 
git remote add canada $SSH_URL 
git push canada

Third, rename the origin remote to usa, then rename the canada remote to origin. Then tell Git to use origin as the default remote. And we're done.

git remote rename origin usa
git remote rename canada origin
git push -u origin master

Fourth, do some fetches and pushes on the new origin remote to ensure that it is working properly.

Fifth, remove the old remote from each repository.

git remote remove usa

Finally, delete the CloudFormation stacks in Virginia, which cleans up all of the CodeCommit resources used.

aws cloudformation delete-stack --stack-name $NAME --region us-east-1