如何从 codebuild 承担 AWS 角色以更新另一个 AWS 账户中的 lambda 函数?

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

我在账户 A 中进行了代码构建,Buildspec 包含更新位于账户 B 中的 lambda 函数的步骤。请注意,S3 包含 zip 文件并且 S3 位于账户 A 中。

附加到 codebuild 的角色是 roleA。

假设我们有 2 个角色:

  1. 账户 A 中的角色 A
  2. 账户 B 中的角色 B

roleA 信任关系政策:

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

已将策略附加到角色 A:

跨账户策略:

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

roleB 信任关系策略:

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

角色 B 的附加策略:

当我 运行 代码构建时,我收到以下错误:

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

构建规范文件:

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

您可以将 resource policy(这与 IAM 策略不同)添加到您的 lambda 函数:

{
  "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>"
    }
  ]
}