简体   繁体   中英

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.

I'm creating a Lambda in CDK and adding a policy statement. 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. I want to give this lambda permissions only to the S3 bucket resource (as opposed to using resources="*" or something). 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).

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.

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 . I understand that I'm not getting the ARN correctly, but I don't know how to get it. 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.

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.

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 ]
         )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM