How to assume an AWS role from codebuild to update lambda function in another AWS account?

Viewed 418

I have codebuild in account A and the Buildspec contains steps to update the lambda function which is located in account B. Note that the S3 contains zip file and S3 is in Account A itself.

Role attached to codebuild is roleA.

Lets say we have 2 roles:

  1. roleA in account A
  2. roleB in account B

roleA Trust Relationship Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "codebuild.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Attached policy to roleA:

  • S3FullAccess
  • CodebuildPolicy
  • LambdaFullAccess
  • CrossAccountPolicy

CrossAccountPolicy:

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::ACCOUNTID_B:role/roleB"
    }
}

roleB Trust Relationship Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::ACCOUNTID_A:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

Attached policy to roleB:

  • AWSLambda_FullAccess

When I run codebuild I'm getting the following error:

An error occurred (AccessDeniedException) when calling the UpdateFunctionCode operation: User: arn:aws:sts::ACCOUNTID_A:assumed-role/roleA/AWSCodeBuild-01f59836-f3e4-9732-d910-ff40967882f9 is not authorized to perform: lambda:UpdateFunctionCode on resource: arn:aws:lambda:us-west-1:ACCOUNTID_B:function:lambdafunctionhere because no resource-based policy allows the lambda:UpdateFunctionCode action

Buildspec file:

version: 0.2

phases:
  build:
    commands:
       - aws --version
       - aws lambda update-function-code --function-name arn:aws:lambda:us-west-1:ACCOUNTID_B:function:lambdafunctionnamehere --s3-bucket s3_zip_accountA --s3-key Lambda/package.zip
1 Answers

You can add a resource policy (this is different then IAM policies) to your lambda function:

{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement": [
    {
      "Sid": "AllowUpdateFunction",
      "Effect": "Allow",
      "Principal": {
        "AWS": "ARN of code build role"
      },
      "Action": "lambda:UpdateFunctionCode",
      "Resource": "<ARN of lambda function>"
    }
  ]
}
Related