[英]How to use Intrinsic Functions in Python AWS CDK?
I'm trying to use Amazon's Intrinsic Functions from their CloudFormation in the Python CDK but I am struggling to get it to work.我正在尝试在 Python CDK 中使用 Amazon 的 CloudFormation 中的内在函数,但我很难让它工作。
I'm creating a Lambda in CDK and adding a policy statement.我正在 CDK 中创建 Lambda 并添加策略声明。 In this policy statement I give the Lambda access to S3 actions to an S3 bucket that is also created in the CDK above it.在此策略声明中,我授予 Lambda 对 S3 存储桶的 S3 操作访问权限,该存储桶也在其上方的 CDK 中创建。 I want to give this lambda permissions only to the S3 bucket resource (as opposed to using resources="*"
or something).我只想将此 lambda 权限授予 S3 存储桶资源(而不是使用resources="*"
或其他东西)。 I realised I'd need the ARN of the bucket before it had been created - so I asked a colleague who said to use Intrinsic Functions (he does CloudFormation but hasn't used the CDK).我意识到在创建存储桶之前我需要它的 ARN - 所以我问了一位说使用内部函数的同事(他使用 CloudFormation 但没有使用 CDK)。
This is where I'm getting stuck - I can't figure out how to use the Intrinsic Functions in order to get the bucket ARN and put that into the resource of the Policy Statement.这就是我卡住的地方——我不知道如何使用内在函数来获取存储桶 ARN 并将其放入策略声明的资源中。
Here's my code:这是我的代码:
bucket_arn = core.Fn.get_att("BucketIDHere", "Arn")
event_lambda.add_to_role_policy(
aws_iam.PolicyStatement(
effect=aws_iam.Effect.ALLOW,
actions=[
"s3:PutObject", "s3:GetObject", "s3:DeleteObject",
"s3:ListBucket", "secretsmanager:GetSecretValue", "kms:*"
],
resources=[
bucket_arn
]))
But I'm getting但我越来越
raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Expected Scalar, got {"$jsii.byref":"@aws-cdk/core.Intrinsic@10012"}
When I try cdk diff
.当我尝试cdk diff
时。 I understand that I'm not getting the ARN correctly, but I don't know how to get it.我了解我没有正确获取 ARN,但我不知道如何获取它。 I've read the docs and know that I probably have to use IResolveable
and IResolveContext
but every attempt I've made to use them has failed.我已经阅读了文档并且知道我可能必须使用IResolveable
和IResolveContext
但我使用它们所做的每一次尝试都失败了。
If someone has an example or some solution that would be much appreciated!如果有人有一个例子或一些解决方案,将不胜感激!
You should try to use high-level constructs as much as possible.您应该尽可能多地使用高级构造。 If you have created a bucket in the same stack, you can get the ARN of the bucket by using bucket_arn
attribute.如果您在同一个堆栈中创建了一个存储桶,您可以通过bucket_arn
属性获取该存储桶的 ARN。
my_bucket = _s3.Bucket(self, "my_bucket")
arn = my_bucket.bucket_arn
You can also import the bucket as a resource if it is not part of your stack.如果存储桶不属于您的堆栈,您也可以将它作为资源导入。
from aws_cdk import aws_s3 as _s3
...
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
bucket = _s3.Bucket.from_bucket_name(self, "an-identifier", "my-bucket-name")
event_lambda.add_to_role_policy(
aws_iam.PolicyStatement(
...
resources=[ bucket.bucket_arn ]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.