sshakya
sshakya

Reputation: 145

AWS CodeBuild: Accessing CodeCommit repository in another account?

I have a CodeCommit repo in Account A, that I would like to use as a source provider for my CodeBuild project in Account B.

I have created a Role in Account A with full codecommit access to Account B. I am lost on how to proceed further with this.

How do I use this role that in Account A in my CodeBuild project that is in Account B?

Upvotes: 0

Views: 1645

Answers (3)

Msv
Msv

Reputation: 1371

After configuring Cross Account access(Only up to role creation in source account is required), Add the policy to assume cross account role for codebuild role.

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "<source role arn>"
    }
}

Now in codebuild project settings select No Source and in buildspec add the below additional steps.

version: 0.2

env:
  shell: bash

phases:
  pre_build:
    commands:
      - echo "Assuming role in source account"
      - CREDS=$(aws sts assume-role --role-arn $ROLE_ARN --role-session-name CodeBuildSession)
      - export AWS_ACCESS_KEY_ID=$(echo $CREDS | jq -r .Credentials.AccessKeyId)
      - export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | jq -r .Credentials.SecretAccessKey)
      - export AWS_SESSION_TOKEN=$(echo $CREDS | jq -r .Credentials.SessionToken)

      # Preparing for cloning
      - git config --global credential.helper '!aws codecommit credential-helper $@'
      - git config --global credential.UseHttpPath true
      - git clone --depth 1 --branch $BRANCH $CLONE_URL

      - unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN

      # cd into repo
      - cd $(basename $CLONE_URL)
      
      - ... Your usual codebuild steps

Upvotes: 0

sshakya
sshakya

Reputation: 145

I realised that I cannot do this directly with CodeBuild so I created a CodePipeline, CMK, and an artifact bucket with the necessary permissions for the source code to get uploaded to it first. I followed this blog post to do it through the console and CLI, and then created CF templates for later re-use.

https://prashant-48386.medium.com/cross-account-codepipeline-that-use-codecommit-from-another-aws-account-9d5ab4c892f6

Upvotes: 0

Daniel Lemke
Daniel Lemke

Reputation: 2459

You can setup a cross-account pipeline using AWS CodePipeline, which accesses the repository from Account A from another account - typically that would your CI/CD account. The CI/CD account then usually also deploys again to other accounts such as Test, QA or Prod.

See this AWS blog post for a description on how this can be implemented. There is also a GitHub example from AWS, along with a accompanying workshop, that guides you through the full process. Just note that the GitHub sample + workshop assume the repo to be in the same account as the pipeline, while the blog post and your scenario have the repo in a different account.

Upvotes: 1

Related Questions