Exemplo n.º 1
0
        Credentials=GetAtt(apiRole, "Arn"),
        Type="AWS_PROXY",
        IntegrationHttpMethod='ANY',
        Uri=Join("", [
            "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/",
            GetAtt(lambdaFunction, "Arn"),
            "/invocations"
        ])
    )
))

stageName = "v1"

apiDeployment = t.add_resource(api.Deployment(
    "apiDeployment",
    DependsOn="apiMethod",
    RestApiId=Ref(restApi),
))

apiStage = t.add_resource(api.Stage(
    "apiStage",
    StageName=stageName,
    RestApiId=Ref(restApi),
    DeploymentId=Ref(apiDeployment)
))

apiKey = t.add_resource(api.ApiKey(
    "apiKey",
    StageKeys=[api.StageKey(
        RestApiId=Ref(restApi),
        StageName=Ref(apiStage)
                                                   "$input.params('whatever')"
                                               }),
                apigateway.IntegrationResponse(
                    "IntegrationResponse",
                    StatusCode="404",
                    SelectionPattern="[a-zA-Z]+.*",  # any error
                    ResponseTemplates={
                        "application/json": "$input.params('whatever')"
                    }),
            ]),
        RequestParameters={
            "method.request.path.param1": True,
            "method.request.querystring.param2": True
        },
        MethodResponses=[
            apigateway.MethodResponse("APIResponse", StatusCode="200"),
            apigateway.MethodResponse("APIResponse", StatusCode="404")
        ]))

api_deployment = template.add_resource(
    apigateway.Deployment("APIDeployment", RestApiId=Ref(api)))

api_stage = template.add_resource(
    apigateway.Stage("APIStage",
                     CacheClusterEnabled=False,
                     DeploymentId=Ref(api_deployment),
                     RestApiId=Ref(api),
                     StageName="live"))

print template.to_json()
Exemplo n.º 3
0
    def add_api(self):
        rest_api = self.add_resource(
            apigateway.RestApi(
                'Api',
                Description=Join(' ',
                                 [Ref(self.domain), 'Terraform Registry']),
                Name=StackName))

        methods = self.add_registry_api(rest_api)
        methods += [self.add_service_discovery_api(rest_api)]

        self.add_resource(
            awslambda.Permission(
                f'ApigatewayPermission',
                Principal='apigateway.amazonaws.com',
                Action='lambda:InvokeFunction',
                FunctionName=Ref(self._lambda_function),
                SourceArn=Join('', [
                    'arn:aws:execute-api:', Region, ':', AccountId, ':',
                    Ref(rest_api), '/*'
                ])))

        deployment_id = 'ApiDeployment' + ''.join(
            random.choice(string.ascii_letters) for _ in range(5))

        deployment = self.add_resource(
            apigateway.Deployment(deployment_id,
                                  Description=self._build_version,
                                  RestApiId=Ref(rest_api),
                                  DependsOn=methods,
                                  DeletionPolicy=Retain))

        stage = self.add_resource(
            apigateway.Stage('ApiStage',
                             MethodSettings=[
                                 apigateway.MethodSetting(
                                     HttpMethod='*',
                                     LoggingLevel='INFO',
                                     MetricsEnabled=True,
                                     ResourcePath='/*',
                                     DataTraceEnabled=True,
                                 )
                             ],
                             TracingEnabled=True,
                             StageName='prd',
                             RestApiId=Ref(rest_api),
                             DeploymentId=Ref(deployment),
                             DependsOn=[deployment]))

        domain = self.add_resource(
            apigateway.DomainName(
                'ApiDomain',
                DomainName=Ref(self.domain),
                CertificateArn=Ref(self.certificate),
                EndpointConfiguration=apigateway.EndpointConfiguration(
                    Types=['EDGE'])))

        mapping = self.add_resource(
            apigateway.BasePathMapping('Mapping',
                                       DomainName=Ref(domain),
                                       RestApiId=Ref(rest_api),
                                       Stage='prd',
                                       DependsOn=['ApiStage']))

        dns_record = self.add_resource(
            route53.RecordSetGroup('ApiDnsRecord',
                                   HostedZoneId=Ref(self.hosted_zone),
                                   RecordSets=[
                                       route53.RecordSet(
                                           Name=Ref(self.domain),
                                           AliasTarget=route53.AliasTarget(
                                               DNSName=GetAtt(
                                                   domain,
                                                   'DistributionDomainName'),
                                               HostedZoneId='Z2FDTNDATAQYW2'),
                                           Type='A')
                                   ]))
                apigateway.IntegrationResponse(
                    "IntegrationResponse",
                    StatusCode="404",
                    SelectionPattern="[a-zA-Z]+.*",  # any error
                    ResponseTemplates={
                        "application/json": "$input.params('whatever')"
                    }),
            ]),
        RequestParameters={
            "method.request.path.param1": True,
            "method.request.querystring.param2": True
        },
        MethodResponses=[
            apigateway.MethodResponse("APIResponse", StatusCode="200"),
            apigateway.MethodResponse("APIResponse", StatusCode="404")
        ]))

api_deployment = template.add_resource(
    apigateway.Deployment("APIDeployment",
                          RestApiId=Ref(api),
                          DependsOn=api_first_method.title))

api_stage = template.add_resource(
    apigateway.Stage("APIStage",
                     CacheClusterEnabled=False,
                     DeploymentId=Ref(api_deployment),
                     RestApiId=Ref(api),
                     StageName="live"))

print(template.to_json())
Exemplo n.º 5
0
        Join("", [
            Ref(api),
            "/*/POST/*"
        ])])
))

t.add_output(Output(
    "RootResourceId",
    Value=GetAtt(api, "RootResourceId")
))

deployment = t.add_resource(apigateway.Deployment(
    "Deployment",
    RestApiId=Ref(api),
    StageDescription=apigateway.StageDescription(
        CacheClusterEnabled=False,
        StageName="dev"
    ),
    StageName="dev"

))

invoke_policy = iam.ManagedPolicy(
    "InvokePolicy",
    PolicyDocument={
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "CreateCert",
                "Effect": "Allow",
                "Action": [
                    "execute-api:Invoke"
Exemplo n.º 6
0
    def build_template(self):

        t = self._init_template()

        swag_data = []
        for i in range(0, 4):
            swag_data.append(
                Ref(
                    t.add_parameter(
                        Parameter('{}Swagger{}'.format(self.stack_name, i),
                                  Type='String',
                                  Default=' ',
                                  Description='Swagger Data #{}'.format(i)))))

        api = t.add_resource(
            apigateway.RestApi(
                '{}RestApi'.format(self.stack_name),
                Body=Join('', swag_data),
                EndpointConfiguration=apigateway.EndpointConfiguration(
                    Types=[self.ep_type])))

        if len(self.stages) <= 0:
            self.add_stage('prod')

        for stage in self.stages:
            deployment = t.add_resource(
                apigateway.Deployment(
                    '{}{}{}Deployment'.format(self.stack_name,
                                              md5str(self.template_str),
                                              stage),
                    RestApiId=Ref(api),
                    StageName=md5str(self.template_str + stage),
                ))
            stage_res = t.add_resource(
                apigateway.Stage(
                    '{}{}Stage'.format(self.stack_name, stage),
                    StageName=stage,
                    Description='{}{}'.format(self.stack_name, stage),
                    RestApiId=Ref(api),
                    DeploymentId=Ref(deployment),
                ))

        for func in self.lambda_funcs:
            func_param = t.add_parameter(
                Parameter(func.output_func_arn(),
                          Type='String',
                          Description='Function to grant invoke access to'))

            t.add_resource(
                awslambda.Permission(
                    'SwagFuncPerm{}'.format(func.output_func_name()),
                    SourceArn=Join("", [
                        'arn:aws:execute-api:',
                        Ref('AWS::Region'), ':',
                        Ref('AWS::AccountId'), ':',
                        Ref(api), "/*/*/*"
                    ]),
                    FunctionName=Ref(func_param),
                    Action='lambda:invokeFunction',
                    Principal='apigateway.amazonaws.com',
                    DependsOn="{}RestApi".format(self.stack_name)))

        t.add_output([
            Output('ApiId'.format(self.stack_name),
                   Description='Root id for API',
                   Value=Ref(api)),
            Output('ApiUrl'.format(self.stack_name),
                   Value=Join('', [
                       Ref(api), '.execute-api.',
                       Ref('AWS::Region'), '.amazonaws.com'
                   ]))
        ])

        return t
Exemplo n.º 7
0
android_register_method = template.add_resource(
    apigateway.Method('AndroidRegisterMethod',
                      RestApiId=Ref(restapi),
                      ResourceId=Ref(android_register_resource),
                      HttpMethod='POST',
                      AuthorizationType='NONE',
                      Integration=apigateway.Integration(
                          Type='AWS_PROXY',
                          IntegrationHttpMethod='POST',
                          Uri=lambda_invocation_arn(android_register_lambda),
                      )))

deployment_v1 = template.add_resource(
    apigateway.Deployment('AndroidRestApiV1',
                          DependsOn=[root_method, android_register_method],
                          RestApiId=Ref(restapi),
                          StageName='v1',
                          StageDescription=apigateway.StageDescription(
                              Description='Devices API version 1.')))

template.add_output(
    Output('DevicesApiId',
           Description='Devices REST API ID.',
           Value=Ref(restapi),
           Export=Export('DevicesApiId')))


def pre_deploy(args):
    authorizer.pre_deploy(args)
    androidregister.pre_deploy(args)

    "FileName",
    Type="String",
    Description="Name of the Swagger file inside S3 bucket"
))

api = template.add_resource(apigateway.RestApi(
    "API",
    Description="My API",
    Name="MyAPI",
    BodyS3Location=apigateway.S3Location(
        Bucket=Ref(param_source_bucket),
        Key=Ref(param_ile_name)
    )
))

api_deployment = template.add_resource(apigateway.Deployment(
    "APIDeployment",
    RestApiId=Ref(api),
    DependsOn=api.title,
))

api_stage = template.add_resource(apigateway.Stage(
    "APIStage",
    CacheClusterEnabled=False,
    DeploymentId=Ref(api_deployment),
    RestApiId=Ref(api),
    StageName="live",
))

print(template.to_json())