How to use cross-account CodeCommit repository with Terraform?

Viewed 135

Right now we are using two AWS accounts with Terraform (INT and PROD). Currently we have the same repositories in both of the accounts, which is obviously not best practice, so I'm trying to set up cross-account access. The goal is to have the repos only on the INT account, and make the CodeBuild project or CodePipeline instance on the PROD account to use those repos. I have already created the necessary policies and roles on both accounts so lack of permission should not be a problem. However, what I'm struggling with is using the INT repos as source for the PROD CodeBuild project for example.

The project's source block is configured in the following way:

source {
    type        = "CODECOMMIT"
    location    = "https://git-codecommit.region.amazonaws.com/v1/repos/example-repo"
    buildspec   = data.local_file.buildspec_local.content
  }

I can't seem to understand how should I proceed here. From my understanding, I should somehow reference the repo in the INT account, but from what I know there's only one way to do that, which is using multiple aws provider blocks with the accounts' access key id and secret key. This solution is not possible for us, since we have to use the company's SSO tool to generate credentials which are valid for 12 hours to use the AWS accounts. I am aware that there are loads of questions regarding cross-account access in AWS, but unfortunately I haven't found one that helps me.

1 Answers

Welcome to the world of AWS Terraform! Not sure how far you have gotten on this, but there are two options for you. Option 1 leverages AWS Cross Account Pipeline . Now I am currently in the process of building this out with terraform, but this would be considered the best practice for this type of development.

If you are just looking to pull in the repos from another account, then you can leverage Codebuild to ssh and clone the repository into your build job. to do this, you will need to create an ssh user in the repo account, which we will label A. You will need the ssh users' User Key and the Public Key. You will create two variables in the parameter store called variable_ssh_key and variable_codecommit_user.

Leveraging the buildspec provided here, you can leverage git clone to pull down any repository you need. The only thing you will need is in Account B to create one repo that stores the buildspec and calls the other repos. See buildspec as a reference.

Related