def __init__(self, scope: Construct, id: str, settings, **kwargs) -> None: super().__init__(scope, id, **kwargs) self.id = id # cdk deploy --parameters StageName=v1 stage = CfnParameter( self, "StageName", default="v1", description="The name of the API Gateway Stage.", type="String", ).value_as_string table_name = f"{id}Table" # Create a dynamodb table table = self.create_dynamodb_table(table_name) # Create function and role for OAuth func_oauth_role = self.create_func_oauth_execution_role(f"{id}-OAuth", table_arn=table.table_arn) func_oauth = self.create_lambda("OAuth", custom_role=func_oauth_role) func_oauth.add_environment("SlackAppClientIdParameterKey", CLIENT_ID_PARAMETER_NAME) func_oauth.add_environment("SlackAppClientSecretParameterKey", CLIENT_SECRET_PARAMETER_NAME) func_oauth.add_environment("SlackAppOAuthDynamoDBTable", table_name) func_oauth.add_environment("SlackChannelIds", ",".join(get_channel_ids(settings))) func_oauth.add_environment("SlackTeamIds", ",".join(get_team_ids(settings))) api = apigw_.LambdaRestApi( self, f"{id}-API", description=f"{id} API", endpoint_configuration=apigw_.EndpointConfiguration(types=[apigw_.EndpointType.REGIONAL]), handler=func_oauth, deploy=False, proxy=False, ) item = api.root.add_resource("oauth2") item.add_method("ANY", apigw_.LambdaIntegration(func_oauth)) # Create APIGW Loggroup for setting retention LogGroup( self, f"{id}-API-LogGroup", log_group_name=f"API-Gateway-Execution-Logs_{api.rest_api_id}/{stage}", retention=RetentionDays.ONE_DAY, ) # Do a new deployment on specific stage new_deployment = apigw_.Deployment(self, f"{id}-API-Deployment", api=api) apigw_.Stage( self, f"{id}-API-Stage", data_trace_enabled=True, description=f"{stage} environment", deployment=new_deployment, logging_level=apigw_.MethodLoggingLevel.INFO, metrics_enabled=True, stage_name=stage, tracing_enabled=False, )
def deploy(self, deployment: aws_apigateway.Deployment) -> aws_apigateway.Stage: return aws_apigateway.Stage( self, "DevStage", deployment=deployment, stage_name="dev", tracing_enabled=False, metrics_enabled=False, )
def deploy(self, deployment: aws_apigateway.Deployment) -> aws_apigateway.Stage: return aws_apigateway.Stage( self, "ProdStage", deployment=deployment, stage_name="prod", tracing_enabled=True, metrics_enabled=True, )
def __init__(self, scope: core.Construct, id: str, api_gateway: aws_apigateway.RestApi, **kwargs): super().__init__(scope, id, **kwargs) deployment = aws_apigateway.Deployment(self, 'APIGWDeployment', api=api_gateway) map(lambda m: deployment.node.add_dependency(m), api_gateway.methods) stage = aws_apigateway.Stage(self, 'Stage', deployment=deployment, stage_name='prod')
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # The code that defines your stack goes here ap_api = aws_apigateway.RestApi(self, id='alpha-price-mule-api', deploy=False) ap_deployment = aws_apigateway.Deployment(self, id='ap-deployment', api=ap_api) aws_apigateway.Stage(self, id='ap-stage', deployment=ap_deployment, stage_name='Prod') ap_api.root.add_method('ANY') ap_deployment2 = aws_apigateway.Deployment(self, id='ap-deployment2', api=ap_api) stagename = aws_apigateway.Stage(self, id='ap-stage2', deployment=ap_deployment2, stage_name='Stage') ap_api.deployment_stage = stagename key_mule = ap_api.add_api_key(id='mule', api_key_name='mule') plan = ap_api.add_usage_plan(id='Usage-plan-mule', name='mule', api_key=key_mule, throttle=aws_apigateway.ThrottleSettings(rate_limit=100, burst_limit=200)) plan.add_api_stage(api=ap_api, stage=ap_api.deployment_stage)
def __init__(self, scope: core.Construct, id: str, stack_log_level: str, back_end_api_name: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Create Serverless Event Processor using Lambda): # Read Lambda Code): try: with open( "api_with_stage_variables/stacks/back_end/lambda_src/serverless_greeter.py", mode="r") as f: greeter_fn_code = f.read() except OSError as e: print("Unable to read Lambda Function Code") raise e greeter_fn = _lambda.Function( self, "secureGreeterFn", function_name=f"greeter_fn_{id}", runtime=_lambda.Runtime.PYTHON_3_7, handler="index.lambda_handler", code=_lambda.InlineCode(greeter_fn_code), timeout=core.Duration.seconds(15), reserved_concurrent_executions=20, environment={ "LOG_LEVEL": f"{stack_log_level}", "Environment": "Production", "ANDON_CORD_PULLED": "False", "RANDOM_SLEEP_ENABLED": "False" }, description= "A simple greeter function, which responds with a timestamp") greeter_fn_version = greeter_fn.latest_version greeter_fn_version_alias = _lambda.Alias( self, "greeterFnMystiqueAutomationAlias", alias_name="MystiqueAutomation", version=greeter_fn_version) greeter_fn_dev_alias = _lambda.Alias(self, "greeterFnDevAlias", alias_name="dev", version=greeter_fn_version) greeter_fn_test_alias = _lambda.Alias(self, "greeterFnTestAlias", alias_name="test", version=greeter_fn_version) greeter_fn_prod_alias = _lambda.Alias(self, "greeterFnProdAlias", alias_name="prod", version=greeter_fn_version) # Create Custom Loggroup # /aws/lambda/function-name greeter_fn_lg = _logs.LogGroup( self, "greeterFnLoggroup", log_group_name=f"/aws/lambda/{greeter_fn.function_name}", retention=_logs.RetentionDays.ONE_WEEK, removal_policy=core.RemovalPolicy.DESTROY) # %% # Create API Gateway wa_api = _apigw.RestApi( self, "backEnd01Api", rest_api_name=f"{back_end_api_name}", # deploy_options=wa_api_dev_stage_options, retain_deployments=False, deploy=False, endpoint_types=[_apigw.EndpointType.EDGE], description= f"{GlobalArgs.OWNER}: API Best Practices. Stage Variables for APIs. This stack deploys an API and integrates with Lambda using Stage Variables." ) wa_api_logs = _logs.LogGroup( self, "waApiLogs", log_group_name=f"/aws/apigateway/{back_end_api_name}/access_logs", removal_policy=core.RemovalPolicy.DESTROY, retention=_logs.RetentionDays.ONE_DAY) ###################################### ## CONFIG FOR API STAGE : DEV ## ###################################### dev_wa_api_deploy = _apigw.Deployment( self, "devDeploy", api=wa_api, description=f"{GlobalArgs.OWNER}: Deployment of 'dev' Api Stage", retain_deployments=False) dev_api_stage = _apigw.Stage( self, "devStage", deployment=dev_wa_api_deploy, stage_name="miztiik-dev", throttling_rate_limit=10, throttling_burst_limit=100, # Log full requests/responses data data_trace_enabled=True, # Enable Detailed CloudWatch Metrics metrics_enabled=True, logging_level=_apigw.MethodLoggingLevel.INFO, access_log_destination=_apigw.LogGroupLogDestination(wa_api_logs), variables={"lambdaAlias": "dev"}) # wa_api.deployment_stage = dev_api_stage test_wa_api_deploy = _apigw.Deployment( self, "testDeploy", api=wa_api, description=f"{GlobalArgs.OWNER}: Deployment of 'test' Api Stage", retain_deployments=False) test_api_stage = _apigw.Stage( self, "testStage", deployment=test_wa_api_deploy, stage_name="miztiik-test", throttling_rate_limit=10, throttling_burst_limit=100, # Log full requests/responses data data_trace_enabled=True, # Enable Detailed CloudWatch Metrics metrics_enabled=True, logging_level=_apigw.MethodLoggingLevel.INFO, access_log_destination=_apigw.LogGroupLogDestination(wa_api_logs), variables={"lambdaAlias": "test"}) wa_api.deployment_stage = test_api_stage prod_wa_api_deploy = _apigw.Deployment( self, "prodDeploy", api=wa_api, description=f"{GlobalArgs.OWNER}: Deployment of 'prod' Api Stage", retain_deployments=False) prod_api_stage = _apigw.Stage( self, "prodStage", deployment=prod_wa_api_deploy, stage_name="miztiik-prod", throttling_rate_limit=10, throttling_burst_limit=100, # Log full requests/responses data data_trace_enabled=True, # Enable Detailed CloudWatch Metrics metrics_enabled=True, logging_level=_apigw.MethodLoggingLevel.INFO, access_log_destination=_apigw.LogGroupLogDestination(wa_api_logs), variables={"lambdaAlias": "prod"}) prod_api_stage.node.add_dependency(test_api_stage) wa_api.deployment_stage = prod_api_stage wa_api_res = wa_api.root.add_resource("wa-api") greeter = wa_api_res.add_resource("greeter") backend_stage_uri = (f"arn:aws:apigateway:" f"{core.Aws.REGION}" f":lambda:path/2015-03-31/functions/" f"{greeter_fn.function_arn}" f":" f"${{stageVariables.lambdaAlias}}" f"/invocations") greeter_method_get = greeter.add_method( http_method="GET", request_parameters={ "method.request.header.InvocationType": True, "method.request.path.mystique": True }, # integration=_apigw.LambdaIntegration( # # handler=greeter_fn, # handler=backend_stage_uri, # proxy=True # ) integration=_apigw.Integration( type=_apigw.IntegrationType.AWS_PROXY, integration_http_method="GET", uri=backend_stage_uri)) # "arn:aws:apigateway:eu-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-2:614517326458:function:${stageVariables.preflightFunction}/invocations", # https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:230023004178:function:greeter_fn_well-architected-api:${stageVariable.lambdaAlias}/invocations # We need to manually add permissions for the stages to invoke # CDK By default adds permission only for the last .deployment_stage ##################################################################### ## CDK BUG: CONDITIONS DOES NOT TAKE EFFECT IN SERVICE PRINCIPAL ## ##################################################################### """ greeter_fn.grant_invoke( _iam.ServicePrincipal( service="apigateway.amazonaws.com", conditions={ "ArnLike": {"aws:SourceArn": "this-does-not-work"} } ) ) """ greeter_fn.add_permission( "allowStageInvocation", principal=_iam.ServicePrincipal("apigateway.amazonaws.com"), # source_arn=f"arn:aws:execute-api:{core.Aws.REGION}:{core.Aws.ACCOUNT_ID}:{wa_api.rest_api_id}/{dev_api_stage.stage_name}/{greeter_method_get.resource.path}" source_arn=greeter_method_get.method_arn.replace( wa_api.deployment_stage.stage_name, "*"), action="lambda:InvokeFunction", ) greeter_fn_dev_alias.add_permission( "greeter_fn_devAliasApiPerms", principal=_iam.ServicePrincipal("apigateway.amazonaws.com"), action="lambda:InvokeFunction", source_arn=greeter_method_get.method_arn.replace( wa_api.deployment_stage.stage_name, "*"), ) greeter_fn_test_alias.add_permission( "greeter_fn_testAliasApiPerms", principal=_iam.ServicePrincipal("apigateway.amazonaws.com"), action="lambda:InvokeFunction", source_arn=greeter_method_get.method_arn.replace( wa_api.deployment_stage.stage_name, "*"), ) greeter_fn_prod_alias.add_permission( "greeter_fn_prodAliasApiPerms", principal=_iam.ServicePrincipal("apigateway.amazonaws.com"), action="lambda:InvokeFunction", source_arn=greeter_method_get.method_arn.replace( wa_api.deployment_stage.stage_name, "*"), ) # Outputs output_0 = core.CfnOutput( self, "AutomationFrom", value=f"{GlobalArgs.SOURCE_INFO}", description= "To know more about this automation stack, check out our github page." ) output_1 = core.CfnOutput( self, "WaApiUrl", value=f"{greeter.url}", description= "Use an utility like curl from the same VPC as the API to invoke it." )
def __init__(self, scope: Construct, id: str, settings, **kwargs) -> None: super().__init__(scope, id, **kwargs) self.id = id # cdk deploy --parameters StageName=v1 stage = CfnParameter( self, "StageName", default="v1", description="The name of the API Gateway Stage.", type="String", ).value_as_string # Create function AsyncWorker self.func_async_worker = self.create_lambda("AsyncWorker", custom_role=None) # Create function SyncWorker self.func_sync_worker = self.create_lambda("SyncWorker", custom_role=None) # Create function and role for ImmediateResponse func_immediate_response_role = self.create_immediate_response_execution_role( f"{id}-ImmediateResponse", settings["ssmparametertokenkey"]) func_immediate_response = self.create_lambda( "ImmediateResponse", custom_role=func_immediate_response_role) func_immediate_response.add_environment( "SlackAppTokenParameterKey", settings["ssmparametertokenkey"]) func_immediate_response.add_environment("SlackCommand", settings["command"]) func_immediate_response.add_environment( "AsyncWorkerLambdaFunctionName", f"{id}-AsyncWorker") func_immediate_response.add_environment("SyncWorkerLambdaFunctionName", f"{id}-SyncWorker") func_immediate_response.add_environment( "SlackChannelIds", ",".join(get_channel_ids(settings))) func_immediate_response.add_environment( "SlackDomains", ",".join(get_team_domains(settings))) func_immediate_response.add_environment( "SlackTeamIds", ",".join(get_team_ids(settings))) api = apigw_.LambdaRestApi( self, f"{id}-API", description=f"{id} API", endpoint_configuration=apigw_.EndpointConfiguration( types=[apigw_.EndpointType.EDGE]), handler=func_immediate_response, deploy=False, ) # Create APIGW Loggroup for setting retention LogGroup( self, f"{id}-API-LogGroup", log_group_name= f"API-Gateway-Execution-Logs_{api.rest_api_id}/{stage}", retention=RetentionDays.ONE_DAY, ) # Do a new deployment on specific stage new_deployment = apigw_.Deployment(self, f"{id}-API-Deployment", api=api) apigw_.Stage( self, f"{id}-API-Stage", data_trace_enabled=False, description=f"{stage} environment", deployment=new_deployment, logging_level=apigw_.MethodLoggingLevel.ERROR, metrics_enabled=True, stage_name=stage, tracing_enabled=False, )
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Create a Lambda function # Code in ./src directory lambda_fn = lambda_.Function( self, "MyFunction", runtime=lambda_.Runtime.PYTHON_3_9, handler="index.handler", code=lambda_.Code.from_asset(os.path.join(DIRNAME, "src")) ) #Input parameter for custom domain name created for API Gateway, ex: apis.example.com custom_domain_name = cdk.CfnParameter(self, "customdomainname", type="String", description="The custom domain name for AWS REST API Gateway") #Input parameter for ACM certificate arn certificate_arn = cdk.CfnParameter(self, "certificatearn", type="String", description="The ACM certificate ARN for custom domain name") #Input parameter for s3 bucket name that has truststore pem file truststore_bucket = cdk.CfnParameter(self, "truststorebucket", type="String", description="The S3 trustsore uri for custom domain name") #Input parameter for public hosted zone id public_zone_id = cdk.CfnParameter(self, "publiczoneid", type="String", description="The public hosted zone id to create a record for custom domain name") #Input parameter for public hosted zone id public_zone_name = cdk.CfnParameter(self, "publiczonename", type="String", description="The public hosted zone name to create a record for custom domain name") # Create the Rest API rest_api = apigateway.RestApi( self, "TLSRestAPI", endpoint_types=[apigateway.EndpointType.REGIONAL], description="RestAPI Gateway to verify mutual TLS", deploy=False, retain_deployments=False, disable_execute_api_endpoint=True ) # Create the custom domain api_domain = apigateway.DomainName( self, "MyDomainName", domain_name=custom_domain_name.value_as_string, certificate=acm.Certificate.from_certificate_arn(self, "cert", certificate_arn.value_as_string), mtls=apigateway.MTLSConfig( bucket=s3.Bucket.from_bucket_name(self, "Bucket", truststore_bucket.value_as_string), key="/truststore.pem" ), security_policy=apigateway.SecurityPolicy.TLS_1_2 ) # Create API deployment deployment = apigateway.Deployment( self, "Deployment", api=rest_api, retain_deployments=False ) # Create prod Stage for deployment stage = apigateway.Stage( self, "prod", deployment=deployment, ) # Create API mapping to custom domain base_path_mapping = apigateway.BasePathMapping(self, "MyBasePathMapping", domain_name=api_domain, rest_api=rest_api, stage=stage ) #Get public hosted zone object public_zone = route53.HostedZone.from_hosted_zone_attributes(self, "publiczone", hosted_zone_id=public_zone_id.value_as_string,zone_name=public_zone_name.value_as_string) #Create A record for custom domain name in public hosted zone #Record name will be taken from custom domain name, ex: for apis.example.com, record name will be apis record = route53.ARecord(self, 'MyAliasRecord', zone=public_zone, record_name=cdk.Fn.select(0,cdk.Fn.split('.',custom_domain_name.value_as_string)), target=route53.RecordTarget.from_alias(targets.ApiGatewayDomain(api_domain)) ) rest_api.deployment_stage = stage # Create URI for lambda function stage_uri = f"arn:aws:apigateway:{cdk.Aws.REGION}:lambda:path/2015-03-31/functions/{lambda_fn.function_arn}/invocations" # Create Lambda Integration integration = apigateway.Integration( type=apigateway.IntegrationType.AWS_PROXY, integration_http_method="POST", uri=stage_uri ) # Create APIGW Method method = rest_api.root.add_method("GET", integration) # Add Lambda permissions lambda_fn.add_permission( "lambdaPermission", action="lambda:InvokeFunction", principal=iam.ServicePrincipal("apigateway.amazonaws.com"), source_arn=method.method_arn.replace( rest_api.deployment_stage.stage_name, "*" ) ) # OUTPUTS cdk.CfnOutput(self, "LambdaFunction", export_name="MyLambdaFunction", value=lambda_fn.function_arn) cdk.CfnOutput(self, "ApigwId", export_name="MyAPIGWID", value=rest_api.rest_api_id) cdk.CfnOutput(self, "CustomDomainName", export_name="MyCustomDomain", value=api_domain.domain_name) cdk.CfnOutput(self, "CustomDomainHostedZone", export_name="MyCustomeZone", value=api_domain.domain_name_alias_hosted_zone_id) cdk.CfnOutput(self, "CustomDomainAlias", export_name="MyCustomAlias", value=api_domain.domain_name_alias_domain_name)
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Create a Lambda function # Code in ./src directory lambda_fn = lambda_.Function(self, "MyFunction", runtime=lambda_.Runtime.PYTHON_3_9, handler="index.handler", code=lambda_.Code.from_asset( os.path.join(DIRNAME, "src"))) # Function version version = lambda_fn.current_version # Create function alias alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", version=version) # Create the Rest API rest_api = apigateway.RestApi( self, "RestApi", endpoint_types=[apigateway.EndpointType.REGIONAL], deploy=False, retain_deployments=False) # Create initial deployment deployment = apigateway.Deployment(self, "Deployment", api=rest_api, retain_deployments=False) # Create prod Stage stage = apigateway.Stage(self, "prod", deployment=deployment, variables={"lambdaAlias": "Prod"}) rest_api.deployment_stage = stage # Create URI for lambda alias stage_uri = f"arn:aws:apigateway:{Aws.REGION}:lambda:path/2015-03-31/functions/{lambda_fn.function_arn}:${{stageVariables.lambdaAlias}}/invocations" # Create Lambda Integration integration = apigateway.Integration( type=apigateway.IntegrationType.AWS_PROXY, integration_http_method="POST", uri=stage_uri) # Create APIGW Method method = rest_api.root.add_method("GET", integration) # Add Lambda permissions lambda_fn.add_permission( "lambdaPermission", action="lambda:InvokeFunction", principal=iam.ServicePrincipal("apigateway.amazonaws.com"), source_arn=method.method_arn.replace( rest_api.deployment_stage.stage_name, "*")) # Add permissions for Prod alias alias.add_permission( "aliasPermission", action="lambda:InvokeFunction", principal=iam.ServicePrincipal("apigateway.amazonaws.com"), source_arn=method.method_arn.replace( rest_api.deployment_stage.stage_name, "*")) # OUTPUTS CfnOutput(self, "LambdaFunction", export_name="MyLambdaFunction", value=lambda_fn.function_arn) CfnOutput(self, "ApigwId", export_name="MyAPIGWID", value=rest_api.rest_api_id) CfnOutput(self, "MethodArn", export_name="MyMethodArn", value=method.method_arn) CfnOutput(self, "StageName", export_name="MyStageName", value=rest_api.deployment_stage.stage_name)