How to use intrinsic functions !sub method in Aws cdk?

Viewed 1620

I want to use this resource below for my cdk app, I using Python for CDK:

'arn:aws:s3:::${LoggingBucket}/AWSLogs/${AWSAccoutID}/*'

Therefore I need to substitute the value of LoggingBucket and AWSAccountID.

Here is what I tried:

bucket = s3.Bucket(self, "my-bucket", bucket_name = 'my-bucket')

core.Fn.sub('arn:aws:s3:::${LoggingBucket}/AWSLogs/${AWSAccoutID}/*',[bucket.bucket_name, core.Environment.account])

But I get this error for line of core.Fn.sub :

AttributeError: type object 'property' has no attribute '__jsii_type__'
Subprocess exited with error 1

Then I tried this as well:

mappings = {
    'LoggingBucket': bucket.bucket_name,
    'AWSAccountID': core.Environment.account
}

core.Fn.sub('arn:aws:s3:::${LoggingBucket}/AWSLogs/${AWSAccoutID}/*',mappings)

$ cdk synth

I still getting the same error as above.

Question:

Please give me a solution on how to use the !sub function in cloudformation in CDK. Let me know what I doing wrong as well.

Thank you.

2 Answers

Since you are using regular python when creating your infrastructure using AWS CDK you can use python's built-in 'format' method:

'arn:aws:s3:::{}/AWSLogs/{}/*'.format(bucket.bucket_name, core.Environment.account)

or using the old way of python string formatting

'arn:aws:s3:::%s/AWSLogs/%s/*' % (bucket.bucket_name, core.Environment.account)

Since you are using Python (or other programming language) there is no need to use the instrinsic functions that Cloudformation provides.

I suggest a more elegant and easy way to format the arn:

arn= f'arn:aws:s3:::{bucket.bucket_name}/AWSLogs/{core.Environment.account}/*'
Related