1515 aws_lambda_python_alpha as lambda_python ,
1616 aws_lambda as lambda_ ,
1717 aws_iam as iam ,
18+ Stack
1819)
1920from constructs import Construct
2021from cdk_nag import NagSuppressions , NagPackSuppression
@@ -39,8 +40,11 @@ def __init__(
3940 role = role ,
4041 ** kwargs ,
4142 )
42- role .attach_inline_policy (_lambda_basic_policy (scope , construct_id ))
43- role .attach_inline_policy (_lambda_vpc_policy (scope , construct_id ))
43+
44+ # Get the actual function name after initialization
45+ function_name = self .function_name
46+
47+ role .attach_inline_policy (_lambda_basic_policy (scope , construct_id , function_name ))
4448
4549
4650class DockerImageFunctionConstruct (lambda_ .DockerImageFunction ):
@@ -62,14 +66,21 @@ def __init__(
6266 role = role ,
6367 ** kwargs ,
6468 )
65- role .attach_inline_policy (_lambda_basic_policy (scope , construct_id ))
66- role .attach_inline_policy (_lambda_vpc_policy (scope , construct_id ))
69+
70+ # Get the actual function name after initialization
71+ function_name = self .function_name
72+
73+ role .attach_inline_policy (_lambda_basic_policy (scope , construct_id , function_name ))
6774
6875
6976def _lambda_basic_policy (
7077 scope : Construct ,
7178 construct_id : str ,
79+ function_name : str
7280):
81+ region = Stack .of (scope ).region
82+ account = Stack .of (scope ).account
83+
7384 policy = iam .Policy (
7485 scope ,
7586 f"{ construct_id } LambdaBasicExecPolicy" ,
@@ -81,40 +92,16 @@ def _lambda_basic_policy(
8192 "logs:CreateLogStream" ,
8293 "logs:PutLogEvents" ,
8394 ],
84- resources = ["*" ],
85- ),
86- ],
87- )
88- NagSuppressions .add_resource_suppressions (
89- construct = policy ,
90- suppressions = [NagPackSuppression (id = "AwsSolutions-IAM5" , reason = "AWSLambdaBasicExecutionRole" )],
91- )
92- return policy
93-
94-
95- def _lambda_vpc_policy (
96- scope : Construct ,
97- construct_id : str ,
98- ):
99- policy = iam .Policy (
100- scope ,
101- f"{ construct_id } LambdaVPCExecPolicy" ,
102- statements = [
103- iam .PolicyStatement (
104- effect = iam .Effect .ALLOW ,
105- actions = [
106- "ec2:CreateNetworkInterface" ,
107- "ec2:DescribeNetworkInterfaces" ,
108- "ec2:DeleteNetworkInterface" ,
109- "ec2:AssignPrivateIpAddresses" ,
110- "ec2:UnassignPrivateIpAddresses" ,
95+ resources = [
96+ f"arn:aws:logs:{ region } :{ account } :log-group:/aws/lambda/{ function_name } " ,
97+ f"arn:aws:logs:{ region } :{ account } :log-group:/aws/lambda/{ function_name } :*"
11198 ],
112- resources = ["*" ],
11399 ),
114100 ],
115101 )
116102 NagSuppressions .add_resource_suppressions (
117103 construct = policy ,
118- suppressions = [NagPackSuppression (id = "AwsSolutions-IAM5" , reason = "AWSLambdaVPCAccessExecutionRole " )],
104+ suppressions = [NagPackSuppression (id = "AwsSolutions-IAM5" , reason = "CloudWatch log groups " )],
119105 )
120106 return policy
107+
0 commit comments