Reputation: 121
I am trying to create a Lambda function in Python using AWS CDK. The challenge is, role property of this function comes from input parameter. If input parameter value is an ARN, then it should use it while creating a lambda. If input parameter value is a blank string, then create a new role explicitly and assign permissions. I was able to get this to work by assigning a dummy role arn and then assign it again.
myLambdaFunction = _lambda.CfnFunction(self,
id = "myFunction",
function_name = "myLambdaFunction",
description = My Lambda Function",
memory_size = 1024,
timeout = 30,
vpc_config=_lambda.CfnFunction.VpcConfigProperty(
security_group_ids=["sg-00000000000000000"],
subnet_ids=["subnet-00000000"]
),
runtime = "PYTHON_3_9",
handler = "lambda-handler.main",
code=_lambda.S3Code(
bucket=my_lambda_code_bucket,
key=inputParams.myLambdaFunctionPackage
),
role = "arn:aws:iam::111111111111:role/Lambda-Role-DUMMY"
)
myLambdaFunction.node.default_child.add_property_deletion_override("Role")
myLambdaFunction.node.default_child.add_property_override(
"Role",
cdk.Fn.condition_if(
"createrolecondition",
my_lambda_role.role_arn,
RoleARNFromInputParameter
)
)
This worked fine.
However, the problem started when I added event source to this lambda function. It automatically tries to create policy using dummy role 11111.
myLambdaFunction.add_event_source(
_lambda_event_source.SqsEventSource(
my_queue,
batch_size=10
)
)
If I run cdk synth after adding event source, it automatically adds a new SQS Policy and allows SQS access to this lambda and it has this dummy Arn, which does not even exist.
Please suggest if there is a better way to use condition when setting the role while creating lambda.
Upvotes: 0
Views: 1075
Reputation: 25659
A requirement to use CloudFormation parameters (deploy-time resolution) introduces complexity to the CDK, which is optimised for synth-time resolutions. To support parameter conditionality, you must repeat the escape-hatch property override pattern from the OP to inject a CfnCondition wherever the parameter value appears.
One such case is when you add a SQS event source to a Function
target. CDK helpfully grants synth-time permissions with this.queue.grantConsumeMessages(target);
(github source), which you noted is problematic. So you will need to inject another CfnCondition
to the generated policy resource. You could also wire up the event target manually and create your own permissions from scratch, but that does not seem easier.
Is there a better way? Avoid Parameters:
In general, we recommend against using AWS CloudFormation parameters with the AWS CDK. Unlike context values or environment variables, the usual way to pass values into your AWS CDK apps without hard-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow.
Upvotes: 1