コード例 #1
0
 def apigw_authorizer_lbd_permission_aws_object(
         self) -> awslambda.Permission:
     if self._apigw_authorizer_lbd_permission_aws_object_cache is NOTHING:
         apigw_authorizer_lbd_permission_logic_id = "LbdPermission{}".format(
             self.apigw_authorizer_logic_id)
         apigw_authorizer_lbd_permission = awslambda.Permission(
             title=apigw_authorizer_lbd_permission_logic_id,
             Action="lambda:InvokeFunction",
             FunctionName=GetAtt(self.lbd_func_aws_object, "Arn"),
             Principal="apigateway.amazonaws.com",
             SourceArn=Sub(
                 "arn:aws:execute-api:${Region}:${AccountId}:${RestApiId}/authorizers/${AuthorizerId}",
                 {
                     "Region": {
                         "Ref": "AWS::Region"
                     },
                     "AccountId": {
                         "Ref": "AWS::AccountId"
                     },
                     "RestApiId": Ref(self.apigw_restapi),
                     "AuthorizerId": Ref(self.apigw_authorizer_aws_object),
                 }),
             DependsOn=[
                 self.apigw_authorizer_aws_object,
                 self.lbd_func_aws_object,
             ])
         self._apigw_authorizer_lbd_permission_aws_object_cache = apigw_authorizer_lbd_permission
     return self._apigw_authorizer_lbd_permission_aws_object_cache
コード例 #2
0
        def associate(self,
                      lbd_permission,
                      lbd_func,
                      api_method,
                      **kwargs):
            lbd_permission.FunctionName = GetAtt(lbd_func, "Arn")
            lbd_permission.Action = "lambda:InvokeFunction"
            lbd_permission.Principal = "apigateway.amazonaws.com"

            try:
                lbd_permission.SourceArn = Sub(
                    "arn:aws:execute-api:${Region}:${AccountId}:${RestApiId}/*/${HttpMethod}/${ResourcePath}",
                    {
                        "Region": {"Ref": "AWS::Region"},
                        "AccountId": {"Ref": "AWS::AccountId"},
                        "RestApiId": Ref(api_method.RestApiId),
                        "HttpMethod": api_method.HttpMethod,
                        "ResourcePath": api_method.Metadata[TROPOSPHERE_METADATA_FIELD_NAME][
                            ResourceLevelField.ApiResource.FULL_PATH]
                    }
                )
            except:
                pass

            x_depends_on_y(lbd_permission, lbd_func)
            x_depends_on_y(lbd_permission, api_method)
コード例 #3
0
    def s3_event_bucket_name_for_cf(self) -> typing.Union[str, Sub]:
        """
        ``s3.Bucket.BucketName`` field value. ``AWS::AccountId`` is included as
        prefix.

        :rtype: Sub

        **中文文档**

        生成存储桶的名称. 由于存储桶的名字是全球唯一的, 并且不分 Region, 所以需要加上
        AWS Account Id 作为名字的前缀, 以避免冲突.
        """
        if self.s3_event_bucket_basename is NOTHING:
            raise TypeError
        if isinstance(self.s3_event_bucket_basename, str):
            return Sub(
                "${AccountId}-${EnvName}-${BucketBasename}",
                {
                    "AccountId": Ref(AWS_ACCOUNT_ID),
                    "EnvName": Ref(self.param_env_name),
                    "BucketBasename": self.s3_event_bucket_basename,
                },
            )
        else:
            raise TypeError
コード例 #4
0
        def associate(self,
                      lbd_permission,
                      lbd_func,
                      api_authorizer,
                      rest_api,
                      authorizer_type_is_token=True,
                      token_authorizer_header="auth",
                      **kwargs):
            lbd_permission.FunctionName = GetAtt(lbd_func, "Arn")
            lbd_permission.Action = "lambda:InvokeFunction"
            lbd_permission.Principal = "apigateway.amazonaws.com"
            lbd_permission.SourceArn = Sub(
                "arn:aws:execute-api:${Region}:${AccountId}:${RestApiId}/authorizers/${AuthorizerId}",
                {
                    "Region": {"Ref": "AWS::Region"},
                    "AccountId": {"Ref": "AWS::AccountId"},
                    "RestApiId": {"Ref": rest_api},
                    "AuthorizerId": Ref(api_authorizer),
                }
            )

            if authorizer_type_is_token:
                api_authorizer.Type = "TOKEN"
                api_authorizer.IdentitySource = "method.request.header.{}".format(
                    token_authorizer_header
                )
                api_authorizer.RestApiId = Ref(rest_api)
                api_authorizer.AuthorizerUri = Sub(
                    "arn:aws:apigateway:${Region}:lambda:path/2015-03-31/functions/${AuthorizerFunctionArn}/invocations",
                    {
                        "Region": {"Ref": "AWS::Region"},
                        "AuthorizerFunctionArn": GetAtt(lbd_func, "Arn"),
                    }
                )
                x_depends_on_y(api_authorizer, lbd_func)
                x_depends_on_y(api_authorizer, rest_api)

            x_depends_on_y(lbd_permission, lbd_func)
            x_depends_on_y(lbd_permission, api_authorizer)
            x_depends_on_y(lbd_permission, rest_api)
コード例 #5
0
 def associate(self, api_method, lbd_func, **kwargs):
     try:
         api_method.Integration.Type = "AWS"
         api_method.Integration.IntegrationHttpMethod = "POST"
         api_method.Integration.Uri = Sub(
             "arn:aws:apigateway:${Region}:lambda:path/2015-03-31/functions/${LambdaArn}/invocations",
             {
                 "Region": {
                     "Ref": "AWS::Region"
                 },
                 "LambdaArn": GetAtt(lbd_func, "Arn"),
             })
     except:
         pass
     x_depends_on_y(api_method, lbd_func)
コード例 #6
0
    def apigw_authorizer_aws_object(self) -> apigateway.Authorizer:
        if self._apigw_authorizer_aws_object_cache is NOTHING:
            if self.apigw_authorizer_name is NOTHING:
                apigw_authorizer_name = self.apigw_authorizer_logic_id
            else:
                apigw_authorizer_name = self.apigw_authorizer_name

            if len(
                    set(apigw_authorizer_name).difference(
                        set(string.ascii_letters + string.digits))):
                raise ValueError(
                    "{}.apigw_authorizer_name can only have letter and digits".
                    format(self.identifier))
            apigw_authorizer = apigateway.Authorizer(
                title=self.apigw_authorizer_logic_id,
                Name=apigw_authorizer_name,
                RestApiId=Ref(self.apigw_restapi),
                AuthType="custom",
                Type="TOKEN",
                IdentitySource="method.request.header.{}".format(
                    self.apigw_authorizer_token_type_header_field),
                AuthorizerResultTtlInSeconds=300,
                AuthorizerUri=Sub(
                    "arn:aws:apigateway:${Region}:lambda:path/2015-03-31/functions/${AuthorizerFunctionArn}/invocations",
                    {
                        "Region": {
                            "Ref": "AWS::Region"
                        },
                        "AuthorizerFunctionArn":
                        GetAtt(self.lbd_func_aws_object, "Arn"),
                    }),
                DependsOn=[
                    self.lbd_func_aws_object,
                    self.apigw_restapi,
                ])
            self._apigw_authorizer_aws_object_cache = apigw_authorizer
        return self._apigw_authorizer_aws_object_cache
コード例 #7
0
    def apigw_method_aws_object(self) -> apigateway.Method:
        if self._apigw_method_aws_object_cache is NOTHING:
            depends_on = [
                self.apigw_resource_aws_object,
                self.lbd_func_aws_object,
            ]

            # Integration Request
            request_template = {"application/json": "$input.json('$')"}

            # Integration Response
            if self.apigw_method_int_type == self.ApiMethodIntType.html:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ResponseParameters={
                        "method.response.header.Access-Control-Allow-Origin":
                        "'*'",
                        "method.response.header.Content-Type": "'text/html'"
                    },
                    ResponseTemplates={"text/html": "$input.path('$')"},
                )
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={
                        "method.response.header.Access-Control-Allow-Origin":
                        False,
                        "method.response.header.Content-Type": False,
                    },
                    ResponseModels={"application/json": "Empty"},
                )
            elif self.apigw_method_int_type == self.ApiMethodIntType.rpc:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ContentHandling="CONVERT_TO_TEXT",
                    ResponseParameters={},
                    ResponseTemplates={"application/json": ""})
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={},
                    ResponseModels={"application/json": "Empty"},
                )
            elif self.apigw_method_int_type == self.ApiMethodIntType.rest:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ContentHandling="CONVERT_TO_TEXT",
                    ResponseParameters={},
                    ResponseTemplates={"application/json": ""})
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={},
                    ResponseModels={"application/json": "Empty"},
                )
            else:
                raise TypeError

            integration_responses = [
                integration_response_200,
            ]

            integration = apigateway.Integration(
                Type="AWS",
                IntegrationHttpMethod="POST",
                Uri=Sub(
                    "arn:aws:apigateway:${Region}:lambda:path/2015-03-31/functions/${LambdaArn}/invocations",
                    {
                        "Region": {
                            "Ref": "AWS::Region"
                        },
                        "LambdaArn": GetAtt(self.lbd_func_aws_object, "Arn"),
                    }),
                RequestTemplates=request_template,
                IntegrationResponses=integration_responses,
            )

            if self.apigw_method_int_passthrough_behavior is not NOTHING:
                integration.PassthroughBehavior = self.apigw_method_int_passthrough_behavior
            if self.apigw_method_int_timeout_in_milli is not NOTHING:
                integration.TimeoutInMillis = self.apigw_method_int_timeout_in_milli

            # Method Response
            method_responses = [
                method_response_200,
            ]

            if self.apigw_method_enable_cors_yes is True:
                for integration_response in integration.IntegrationResponses:
                    integration_response.ResponseParameters[
                        "method.response.header.Access-Control-Allow-Origin"] = "'*'"

                for method_response in method_responses:
                    method_response.ResponseParameters[
                        "method.response.header.Access-Control-Allow-Origin"] = False

            self.check_apigw_method_authorization_type()
            self.check_apigw_method_int_type()

            apigw_method = apigateway.Method(
                title=self.apigw_method_logic_id,
                RestApiId=Ref(self.apigw_restapi),
                ResourceId=Ref(self.apigw_resource_aws_object),
                AuthorizationType=self.apigw_method_authorization_type,
                HttpMethod=self.apigw_method_http_method,
                MethodResponses=method_responses,
                Integration=integration,
            )

            if self.apigw_method_use_authorizer_yes:
                apigw_method.AuthorizerId = Ref(self.apigw_method_authorizer)
                depends_on.append(self.apigw_method_authorizer)

            apigw_method.DependsOn = depends_on

            self._apigw_method_aws_object_cache = apigw_method

        return self._apigw_method_aws_object_cache
コード例 #8
0
        AWSServiceName.amazon_Kinesis_Data_Firehose,
    ]),
    ManagedPolicyArns=[
        AWSManagedPolicyArn.administratorAccess,
    ])

kinesis_delivery_stream = firehose.DeliveryStream(
    "KinesisDeliveryStream",
    template=template,
    DeliveryStreamName=helper_fn_sub("{}-web-event", param_env_name),
    DeliveryStreamType="DirectPut",
    ExtendedS3DestinationConfiguration=firehose.
    ExtendedS3DestinationConfiguration(
        BucketARN="arn:aws:s3:::eq-sanhe-for-everything",
        Prefix=Sub(
            "data/kinesis-analytics/${EnvironmentName}/year=!{timestamp:YYYY}/month=!{timestamp:MM}/day=!{timestamp:dd}/hour=!{timestamp:HH}/minute=!{timestamp:mm}/",
            {"EnvironmentName": Ref(param_env_name)}),
        ErrorOutputPrefix=Sub(
            "data/kinesis-analytics/${EnvironmentName}/result=!{firehose:error-output-type}/year=!{timestamp:YYYY}/month=!{timestamp:MM}/day=!{timestamp:dd}/hour=!{timestamp:HH}/minute=!{timestamp:mm}/",
            {"EnvironmentName": Ref(param_env_name)}),
        BufferingHints=firehose.BufferingHints(IntervalInSeconds=60,
                                               SizeInMBs=5),
        CompressionFormat="UNCOMPRESSED",
        RoleARN=kinesis_delivery_stream_role.iam_role_arn,
        S3BackupMode="Disabled",
    ))

# Kinesis Analytics Application
kinesis_analytics_application_role = iam.Role(
    "KinesisAnalyticsApplicationServiceRole",
    template=template,
コード例 #9
0
    def create_template(self):
        # ELBのログを保存する
        elb_log_bucket = self.tpl.add_resource(
            s3.Bucket(
                'ElbLogBucket',
                BucketName=f'{self.prefix}-{self.project}-lb-log-bucket',
            ))

        # ELBの論理IDをアウトプット
        self.tpl.add_output(
            Output('ElbLogBucket',
                   Description='LoadBalancer Log Bucket',
                   Value=Ref(elb_log_bucket)))

        # ELBのログを保存させるためのBucketPolicyを作成
        self.tpl.add_resource(
            s3.BucketPolicy(
                'AlbLogPolicy',
                Bucket=Ref(elb_log_bucket),
                PolicyDocument={
                    'Version':
                    '2012-10-17',
                    'Statement': [{
                        'Effect':
                        'Allow',
                        'Principal': {
                            'AWS': 'arn:aws:iam::582318560864:root'
                        },
                        'Action':
                        's3:PutObject',
                        'Resource':
                        Sub(f'arn:aws:s3:::${{{elb_log_bucket.title}}}/AWSLogs/${{{AWS_ACCOUNT_ID}}}/*'
                            )
                    }, {
                        'Effect':
                        'Allow',
                        'Principal': {
                            'Service': 'delivery.logs.amazonaws.com'
                        },
                        'Action':
                        's3:PutObject',
                        'Resource':
                        Sub(f'arn:aws:s3:::${{{elb_log_bucket.title}}}/AWSLogs/${{{AWS_ACCOUNT_ID}}}/*'
                            ),
                        'Condition': {
                            'StringEquals': {
                                's3:x-amz-acl': 'bucket-owner-full-control'
                            }
                        }
                    }, {
                        'Effect':
                        'Allow',
                        'Principal': {
                            'Service': 'delivery.logs.amazonaws.com'
                        },
                        'Action':
                        's3:GetBucketAcl',
                        'Resource':
                        Sub(f'arn:aws:s3:::${{{elb_log_bucket.title}}}')
                    }]
                }))