| 7 | import cdk_nag as nag |
| 8 | |
| 9 | class LambdaNagExampleStack(Stack): |
| 10 | def __init__(self, app: App, id: str) -> None: |
| 11 | super().__init__(app, id) |
| 12 | |
| 13 | # Building Role |
| 14 | lambda_func_role = iam.Role(self, "lambda-nag-func-role-example", |
| 15 | assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"), |
| 16 | description="A simple role detached from self CDK built role" |
| 17 | ) |
| 18 | lambda_func_role_policy = iam.Policy( |
| 19 | self, "lambda-nag-func-role-policy-example", |
| 20 | statements=[ |
| 21 | iam.PolicyStatement( |
| 22 | actions=[ |
| 23 | "logs:CreateLogStream", |
| 24 | "logs:PutLogEvents", |
| 25 | "logs:CreateLogGroup" |
| 26 | ], |
| 27 | resources=[ |
| 28 | "*" |
| 29 | ] |
| 30 | ) |
| 31 | ], |
| 32 | roles=[lambda_func_role] |
| 33 | ) |
| 34 | |
| 35 | # In case of wildcard policy usage you must add a suppression in order to give a reason for that. |
| 36 | nag.NagSuppressions.add_resource_suppressions( |
| 37 | lambda_func_role_policy, |
| 38 | [{ |
| 39 | "id": "AwsSolutions-IAM5", |
| 40 | "reason": "A wildcard is necessary over this policy because <put your reason here>..." |
| 41 | }] |
| 42 | ) |
| 43 | |
| 44 | with open("lambda-func/lambda-handler.py", encoding="utf8") as fcn_file: |
| 45 | handler_code = fcn_file.read() |
| 46 | |
| 47 | # A non-container Lambda function is not configured to use the latest runtime version can raise a new error |
| 48 | lambda_func = lambda_.Function( |
| 49 | self, "lambda-nag-func-example", |
| 50 | code=lambda_.InlineCode(handler_code), |
| 51 | handler="index.handler", |
| 52 | timeout=Duration.seconds(30), |
| 53 | role=lambda_func_role, |
| 54 | runtime=lambda_.Runtime.PYTHON_3_12, |
| 55 | ) |
| 56 | |
| 57 | app = App() |
| 58 | LambdaNagExampleStack(app, "LambdaNagExampleStack") |