Пример #1
0
    def __init__(self, scope: core.Construct, id: str, common_stack: CommonStack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self._supported_in_region = self.is_service_supported_in_region()

        # Create API
        api = apigateway.RestApi(self, "testApi")

        # Generate a random API key, add it to the underlying CloudFormation
        # resource of the Construct so that we can use it in our tests.
        api_key_value = self.random_hex(20)
        api_key = api.add_api_key("testKey")
        cfn_api_key = api_key.node.default_child
        cfn_api_key.add_property_override("Value", api_key_value)

        # Create Usage Plan and add it to the API
        plan = api.add_usage_plan("usagePlan", api_key=api_key)
        plan.add_api_stage(stage=api.deployment_stage)

        # Create resources in API
        echo = api.root.add_resource("echo")
        echo_post = echo.add_resource("post")
        auth = api.root.add_resource("auth")
        apikey = api.root.add_resource("apikey")

        # Wire up methods
        get_url = self.HTTPBIN_URL_TEMPLATE.format(method="get")
        post_url = self.HTTPBIN_URL_TEMPLATE.format(method="post")

        get_integration = apigateway.HttpIntegration(get_url)
        post_integration = apigateway.HttpIntegration(post_url, http_method="POST")
        options_integration = apigateway.HttpIntegration(get_url, http_method="OPTIONS")
        head_integration = apigateway.HttpIntegration(get_url, http_method="HEAD")

        echo.add_method("GET", get_integration)
        echo.add_method("OPTIONS", options_integration)
        echo.add_method("HEAD", head_integration)
        echo_post.add_method("POST", post_integration)
        auth.add_method("GET", get_integration, authorization_type=apigateway.AuthorizationType.IAM)
        apikey.add_method("GET", get_integration, api_key_required=True)

        # Generate all methods for /echo
        for method in ("put", "post", "delete", "patch"):
            url = self.HTTPBIN_URL_TEMPLATE.format(method=method)
            integration = apigateway.HttpIntegration(url, http_method=method)
            echo.add_method(method.upper(), integration)

        # Create SSM parameters for the endpoint of the API and the API key

        self._parameters_to_save = {"endpoint": api.url, "api_key": api_key_value}
        self.save_parameters_in_parameter_store(platform=Platform.ANDROID)

        common_stack.add_to_common_role_policies(self)
Пример #2
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        my_table = _dynamodb.Table(self,
                                   id='dynamoTable',
                                   table_name='testcdktable',
                                   partition_key=_dynamodb.Attribute(
                                       name='lastname',
                                       type=_dynamodb.AttributeType.STRING))

        my_stream = _kinesis.Stream(self,
                                    id='kinesistream',
                                    stream_name='cdkkinesisstream')

        my_bucket = _s3.Bucket(self, id='s3bucket', bucket_name='rajcdkbucket')

        my_lambda = _lambda.Function(self,
                                     id='lambdafunction',
                                     runtime=_lambda.Runtime.PYTHON_3_7,
                                     handler='hello.handler',
                                     code=_lambda.Code.asset('lambdacode'))

        my_api = _apigateway.LambdaRestApi(self,
                                           id='lambdaapi',
                                           rest_api_name='cdkapi',
                                           handler=my_lambda)

        api_with_method = _apigateway.RestApi(self,
                                              id='restapi',
                                              rest_api_name='cdkrestapi_music')
        #music = api_with_method.root.addResource('music')
        #music.addMethod('GET')
        music = api_with_method.root.add_resource('music')
        music.add_method('GET')
        music.add_method("DELETE",
                         _apigateway.HttpIntegration("http://aws.amazon.com"))
    def __init__(self, scope: core.Construct, id: str, wiki_api_endpoint,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create API Gateway):
        api_01 = _apigw.RestApi(self,
                                'apiEndpoint',
                                rest_api_name='mystique-wiki-api',
                                deploy_options=_apigw.StageOptions(
                                    stage_name="myst",
                                    data_trace_enabled=True,
                                    tracing_enabled=True))
        v1 = api_01.root.add_resource("v1")

        # Add resource for HTTP Endpoint: API Hosted on EC2
        self.wiki_url_path_00 = v1.add_resource('wiki_url')
        wiki_url_path_01 = self.wiki_url_path_00.add_resource('{needle}')

        # Create the API Gateway Integration Responses
        list_objects_responses = [
            _apigw.IntegrationResponse(
                status_code="200",
                response_parameters={
                    'method.response.header.Timestamp':
                    'integration.response.header.Date',
                    'method.response.header.Content-Length':
                    'integration.response.header.Content-Length',
                    'method.response.header.Content-Type':
                    'integration.response.header.Content-Type'
                })
        ]

        # Create the API Gateway Integration Request Path mapping
        wiki_url_integration_options = _apigw.IntegrationOptions(
            integration_responses=list_objects_responses,
            request_parameters={
                "integration.request.path.needle": "method.request.path.needle"
            })

        wiki_url_integration = _apigw.HttpIntegration(
            url=f'http://{wiki_api_endpoint}/api/{{needle}}',
            http_method='GET',
            options=wiki_url_integration_options,
            proxy=False,
        )

        wiki_url_method = wiki_url_path_01.add_method(
            "GET",
            wiki_url_integration,
            request_parameters={
                'method.request.header.Content-Type': False,
                'method.request.path.needle': True
            },
            method_responses=[
                _apigw.MethodResponse(
                    status_code="200",
                    response_parameters={
                        'method.response.header.Timestamp': False,
                        'method.response.header.Content-Length': False,
                        'method.response.header.Content-Type': False
                    },
                    response_models={'application/json': _apigw.EmptyModel()})
            ])
        ###########################################
        ################# OUTPUTS #################
        ###########################################
        output_0 = core.CfnOutput(
            self,
            "AutomationFrom",
            value=f"{global_args.SOURCE_INFO}",
            description=
            "To know more about this automation stack, check out our github page."
        )

        output_1 = core.CfnOutput(
            self,
            "GetWikiUrl",
            value=f"{self.wiki_url_path_00.url}/search term",
            description=f"Get Wiki Url for given topic using API Gateway")
        """
Пример #4
0
    def __init__(self,
                 scope: core.Construct,
                 id: str,
                 stack_name: str,
                 task_definition_cpu: int,
                 task_definition_memory_limit_mib: int,
                 docker_image_name: str,
                 container_port: int,
                 desired_container_count: int,
                 private_subnets: Sequence[aws_ec2.Subnet] = None,
                 public_subnets: Sequence[aws_ec2.Subnet] = None,
                 private_security_group: aws_ec2.SecurityGroup = None,
                 public_security_group: aws_ec2.SecurityGroup = None,
                 vpc: aws_ec2.Vpc = None,
                 fargate_cluster: aws_ecs.Cluster = None,
                 authorizer_lambda_arn: str = None,
                 authorizer_lambda_role_arn: str = None,
                 **kwargs):
        super().__init__(scope, id, **kwargs)

        # Role
        self.role = aws_iam.Role(
            self,
            'Role',
            assumed_by=aws_iam.ServicePrincipal(service='ecs.amazonaws.com'),
            managed_policies=[
                aws_iam.ManagedPolicy.from_aws_managed_policy_name(
                    managed_policy_name=
                    'service-role/AmazonECSTaskExecutionRolePolicy')
            ],
            inline_policies={
                id:
                aws_iam.PolicyDocument(statements=[
                    aws_iam.PolicyStatement(
                        effect=aws_iam.Effect.ALLOW,
                        actions=[
                            'kms:Encrypt',
                            'kms:Decrypt',
                            'kms:ReEncrypt*',
                            'kms:GenerateDataKey*',
                            'kms:DescribeKey',
                            'ec2:CreateNetworkInterface',
                            'ec2:DescribeNetworkInterfaces',
                            'ec2:DeleteNetworkInterface',
                            # Remaining actions from https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-ecs.html
                            'elasticloadbalancing:DeregisterInstancesFromLoadBalancer',
                            'elasticloadbalancing:DeregisterTargets',
                            'elasticloadbalancing:Describe*',
                            'elasticloadbalancing:RegisterInstancesWithLoadBalancer',
                            'elasticloadbalancing:RegisterTargets',
                            'ec2:Describe*',
                            'ec2:AuthorizeSecurityGroupIngress'
                        ],
                        resources=['*'])
                ])
            })
        self.role.assume_role_policy.add_statements(
            aws_iam.PolicyStatement(
                actions=['sts:AssumeRole'],
                principals=[
                    aws_iam.ServicePrincipal(service='ecs-tasks.amazonaws.com')
                ]))

        # Set Defaults if parameters are None
        if vpc is None:
            vpc = aws_ec2.Vpc(self, 'Vpc')

        if private_subnets is None:
            private_subnets = vpc.private_subnets

        if public_subnets is None:
            public_subnets = vpc.public_subnets

        if public_security_group is None:
            public_security_group = aws_ec2.SecurityGroup(
                self, 'PublicSecurityGroup', vpc=vpc, allow_all_outbound=True)
            # Allow inbound HTTP traffic
            public_security_group.add_ingress_rule(
                peer=aws_ec2.Peer.ipv4(cidr_ip='0.0.0.0/0'),
                connection=aws_ec2.Port.tcp(port=80))
            # Allow inbound HTTPS traffic
            public_security_group.add_ingress_rule(
                peer=aws_ec2.Peer.ipv4(cidr_ip='0.0.0.0/0'),
                connection=aws_ec2.Port.tcp(port=443))

        if private_security_group is None:
            private_security_group = aws_ec2.SecurityGroup(
                self, 'PrivateSecurityGroup', vpc=vpc, allow_all_outbound=True)

            public_subnet_cidr_blocks = Utils.get_subnet_cidr_blocks(
                public_subnets)

            # Create an ingress rule for each of the NLB's subnet's CIDR ranges and add the rules to the ECS service's
            # security group.  This will allow requests from the NLB to go into the ECS service.  This allow inbound
            # traffic from public subnets.
            for cidr_block in public_subnet_cidr_blocks:
                private_security_group.add_ingress_rule(
                    peer=aws_ec2.Peer.ipv4(cidr_ip=cidr_block),
                    connection=aws_ec2.Port.tcp(port=container_port))

        if fargate_cluster is None:
            fargate_cluster = aws_ecs.Cluster(
                self,
                'FargateCluster',
            )

        task_def = aws_ecs.FargateTaskDefinition(
            self,
            'TaskDefinition',
            cpu=task_definition_cpu,
            memory_limit_mib=task_definition_memory_limit_mib,
            task_role=self.role,
            execution_role=self.role)

        container = aws_ecs.ContainerDefinition(
            self,
            'Container',
            image=aws_ecs.ContainerImage.from_registry(name=docker_image_name),
            task_definition=task_def,
            logging=aws_ecs.AwsLogDriver(stream_prefix='/ecs'))
        container.add_port_mappings(
            aws_ecs.PortMapping(container_port=container_port,
                                protocol=aws_ec2.Protocol.TCP))

        ecs_service = aws_ecs.FargateService(
            self,
            'FargateService',
            cluster=fargate_cluster,
            task_definition=task_def,
            vpc_subnets=aws_ec2.SubnetSelection(subnets=private_subnets),
            security_group=private_security_group,
            desired_count=desired_container_count)

        target_group = aws_elasticloadbalancingv2.NetworkTargetGroup(
            self,
            'TargetGroup',
            port=80,  # Health check occurs over HTTP
            health_check=aws_elasticloadbalancingv2.HealthCheck(
                protocol=aws_elasticloadbalancingv2.Protocol.TCP),
            targets=[ecs_service],
            vpc=vpc)

        nlb = aws_elasticloadbalancingv2.NetworkLoadBalancer(
            self,
            'NetworkLoadBalancer',
            vpc=vpc,
            internet_facing=False,
            vpc_subnets=aws_ec2.SubnetSelection(subnets=public_subnets),
        )
        nlb.add_listener(
            id='Listener',
            port=80,  # HTTP listener
            default_target_groups=[target_group])

        # nlb.log_access_logs(  # todo:  add this later when you have time to research the correct bucket policy.
        #     bucket=aws_s3.Bucket(
        #         self, 'LoadBalancerLogBucket',
        #         bucket_name='load-balancer-logs',
        #         public_read_access=False,
        #         block_public_access=aws_s3.BlockPublicAccess(
        #             block_public_policy=True,
        #             restrict_public_buckets=True
        #         )
        #     )
        # )

        # Dependencies
        ecs_service.node.add_dependency(nlb)

        # API Gateway
        rest_api = aws_apigateway.RestApi(self, stack_name)
        resource = rest_api.root.add_resource(
            path_part='{proxy+}',
            default_method_options=aws_apigateway.MethodOptions(
                request_parameters={'method.request.path.proxy': True}))

        token_authorizer = None
        if authorizer_lambda_arn and authorizer_lambda_role_arn:
            token_authorizer = aws_apigateway.TokenAuthorizer(  #todo: make this a parameter?
                self,
                'JwtTokenAuthorizer',
                results_cache_ttl=core.Duration.minutes(5),
                identity_source='method.request.header.Authorization',
                assume_role=aws_iam.Role.from_role_arn(
                    self,
                    'AuthorizerLambdaInvokationRole',
                    role_arn=authorizer_lambda_role_arn),
                handler=aws_lambda.Function.from_function_arn(
                    self,
                    'AuthorizerLambda',
                    function_arn=authorizer_lambda_arn))

        resource.add_method(
            http_method='ANY',
            authorization_type=aws_apigateway.AuthorizationType.CUSTOM,
            authorizer=token_authorizer,
            integration=aws_apigateway.HttpIntegration(
                url=f'http://{nlb.load_balancer_dns_name}/{{proxy}}',
                http_method='ANY',
                proxy=True,
                options=aws_apigateway.IntegrationOptions(
                    request_parameters={
                        'integration.request.path.proxy':
                        'method.request.path.proxy'
                    },
                    connection_type=aws_apigateway.ConnectionType.VPC_LINK,
                    vpc_link=aws_apigateway.VpcLink(
                        self,
                        'VpcLink',
                        description=
                        f'API Gateway VPC Link to internal NLB for {stack_name}',
                        vpc_link_name=stack_name,
                        targets=[nlb]))))
Пример #5
0
    def __init__(self, scope: cdk.Construct, construct_id: str,
        user_pool=None,
        user_pool_domain=None,
        hello_lambda=None,
        web_bucket=None,
        **kwargs) -> None:

        super().__init__(scope, construct_id, **kwargs)

        api = api_gateway.RestApi(self, "demo-api")

        auth = api_gateway.CognitoUserPoolsAuthorizer(self, "helloAuthorizer",
            cognito_user_pools=[user_pool]
        )
        hello_resource = api.root.add_resource('hello')
        hello_resource.add_method("GET", api_gateway.LambdaIntegration(hello_lambda),
            authorizer=auth,
            authorization_type=api_gateway.AuthorizationType.COGNITO)

        login_resource = api.root.add_resource('login')
        login_resource.add_method("GET", api_gateway.HttpIntegration(user_pool_domain.base_url()))

        web_resource = api.root.add_resource('web')
        file_resource = web_resource.add_resource('{file}')

        s3_access_role = iam.Role(self, "S3AccessRole",
            assumed_by=iam.ServicePrincipal('apigateway.amazonaws.com'),
            managed_policies=[
                iam.ManagedPolicy.from_aws_managed_policy_name('AmazonS3ReadOnlyAccess')
            ]
        )

        file_resource.add_method("GET", api_gateway.AwsIntegration(
            service="s3",
            integration_http_method='GET',
            path="{}/{{item}}".format(web_bucket.bucket_name),
            options={
                'credentials_role': s3_access_role,
                'integration_responses': [
                    {
                        'statusCode': "200",
                        'response_parameters': {
                            'method.response.header.Content-Type': 'integration.response.header.Content-Type'
                        }
                    }
                ],
                'request_parameters': {
                        'integration.request.path.item': 'method.request.path.file',
                        'integration.request.header.Content-Type': 'method.request.header.Content-Type'
                    }
            }),
            request_parameters={
                'method.request.path.file': True,
                'method.request.header.Content-Type': False
            },
            method_responses=[
                {
                    'statusCode': "200",
                    'response_parameters': {
                        'method.response.header.Content-Type': True
                    }
                }
            ],
        )

        self.api_gateway =api