in centralized_vpc_endpoints/centralized_vpc_endpoints_stack.py [0:0]
def __init__(self, scope: cdk.Construct, construct_id: str, services: List, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
vpc_id = core.CfnParameter(
self,
"VPCId",
description="The VPC that you want to use the centralised endpoints in.",
type="AWS::EC2::VPC::Id",
allowed_pattern="^vpc-.*$",
).value_as_string
assume_role_arn = core.CfnParameter(
self,
"R53HubRoleToAssume",
description="The R53 Role in the Hub Account that allows us to Authorize a VPC to the Private Hosted Zone",
allowed_pattern=r"^arn:aws:iam::[\d]{12}:role/.*$",
).value_as_string
# R53Lambda Role
associate_vpc_lambda_role = iam.Role(
self, "associate_vpc_lambda_role", assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
associate_vpc_lambda_role.add_managed_policy(
iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole")
)
associate_vpc_lambda_role.add_managed_policy(
iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaVPCAccessExecutionRole")
)
# Add permissions to the Lambda Role for R53 and AssumeRole
associate_vpc_lambda_role.add_to_policy(
iam.PolicyStatement(effect=iam.Effect.ALLOW, resources=["*"], actions=["ec2:DescribeVpcs"])
)
associate_vpc_lambda_role.add_to_policy(
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
resources=[
"arn:aws:route53:::hostedzone/*",
f"arn:aws:ec2:{core.Aws.REGION}:{core.Aws.ACCOUNT_ID}:vpc/{vpc_id}",
],
actions=["route53:AssociateVPCWithHostedZone", "route53:DisassociateVPCFromHostedZone"],
)
)
# Add permissions to the Lambda Role for Assume Role
associate_vpc_lambda_role.add_to_policy(
iam.PolicyStatement(effect=iam.Effect.ALLOW, resources=[assume_role_arn], actions=["sts:AssumeRole"])
)
R53_Lambda = _lambda.Function(
self,
"R53AuthenticateAssociateVPC",
runtime=_lambda.Runtime.PYTHON_3_7,
code=_lambda.Code.from_asset("lambda"),
handler="R53Associate.handler",
role=associate_vpc_lambda_role,
)
provider_for_r53_lambda = custom_resources.Provider(
self,
"Provider_For_R53_Lambda",
on_event_handler=R53_Lambda,
log_retention=logs.RetentionDays.ONE_DAY, # default is INFINITE
)
# The list of services are in the app.py file
for service in services:
service_hosted_zone_id = core.CfnParameter(
self,
f"Route53DomainIDFor{service.upper()}",
description=f"The route53 hosted zone id from the hub stack for the the {service.upper()} service, \
the string before the colon in <route53 hosted zone id>:<regional vpc endpoint dns name>",
allowed_pattern="^[A-Z0-9]{1,32}$",
).value_as_string
core.CustomResource(
self,
f"R53AssociateCustomResourceFor{service.upper()}",
service_token=provider_for_r53_lambda.service_token,
properties={
"VPCID": vpc_id,
"HostedZoneID": service_hosted_zone_id,
"AccountID": core.Aws.ACCOUNT_ID,
"RoleARN": assume_role_arn,
},
)