是否可以在与 cloudformation 不同的帐户中调用 lambda?

Is it a possible to call a lambda in different account from the cloudformation one?

我在一个帐户上有一个 lambda 并附有此策略:

{
  "Sid": "Id-123",
  "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::115333656057:root"},
  "Action": "lambda:InvokeFunction",
  "Resource": "arn:aws:lambda:eu-central-1:260143830488:function:CentralInstanceScheduler-InstanceSchedulerMain"
}

当我从帐户 115333656057 创建堆栈时,我的用户试图执行 lambda,我收到此错误:

  User: arn:aws:iam::115333656057:user/uguesm is not authorized to perform: lambda:InvokeFunction on resource: arn:aws:lambda:eu-central-1:260143830488:function:CentralizedInstanceScheduler-InstanceSchedulerMain

我做错了什么?

在帐户 260143830488 中 - 编辑您的角色以将策略添加到 InvokeFunction 和另一个帐户的信任策略。

权限:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:eu-central-1:260143830488:function:CentralInstanceScheduler-InstanceSchedulerMain"
    },
  ]
}

信任关系政策:

{
  "Sid": "Id-123",
  "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::115333656057:role/<lambda-role>"},
  "Action": "sts:AssumeRole",
}

在帐户 115333656057 中 - 为 AssumeRole 创建一个 lambda 执行角色

权限:

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::260143830488:role/<RoleName>"
  }
}

信任关系政策:

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

您可以使用 Lambda resource-based policy 来完成。这是直接存在于 Lambda 上的策略。使用基于资源的策略来避免需要创建额外的角色并使用 STS::AssumeRole.

在 CDK 中,它看起来像这样:

        account = 123456789012
        lambda_.CfnPermission(
            scope,
            f"XAccountInvocation{account}",
            action="lambda:InvokeFunction",
            function_name=handler.function_name,
            principal=f"arn:aws:iam::{account}:root",
        )