Ejemplo n.º 1
0
    def __init__(self, key):
        # Resources
        R_RestApi = agw.RestApi('ApiGatewayRestApi')
        auto_get_props(R_RestApi, mapname='')
        R_RestApi.EndpointConfiguration = agw.EndpointConfiguration(
            Types=get_endvalue('EndpointConfiguration'))
        R_RestApi.Policy = IAMPolicyApiGatewayPrivate()
        try:
            condition = cfg.PolicyCondition
            R_RestApi.Policy['Statement'][0]['Condition'] = condition
        except:
            pass

        add_obj([
            R_RestApi,
        ])

        for n, v in getattr(cfg, key).items():
            resname = f'{key}{n}'
            agw_stage = cfg.Stage
            r_Resource = ApiGatewayResource(resname, key=v, stage=agw_stage)

            for m, w in v['Method'].items():
                r_Method = ApiGatewayMethod(f'{resname}Method{m}',
                                            key=w,
                                            basename=n,
                                            name=m,
                                            stage=agw_stage)

                add_obj([
                    r_Resource,
                    r_Method,
                ])

        for n, v in cfg.Lambda.items():
            r_LambdaPermission = LambdaPermissionApiGateway(
                f'LambdaPermission{n}',
                name=Ref(f'Lambda{n}'),
                source=Sub('arn:aws:execute-api:${AWS::Region}:'
                           '${AWS::AccountId}:${ApiGatewayRestApi}/*/*/*'))

            add_obj(r_LambdaPermission)
Ejemplo n.º 2
0
    "lambdaFunction",
    FunctionName="GDACK",
    Code=Code(
        S3Bucket=Ref(lambdaBucket),
        S3Key=Ref(lambdaKey)
    ),
    Description="GDACK Function",
    Handler="index.handler",
    Role=GetAtt(lambdaRole, "Arn"),
    Runtime="python3.6",
    MemorySize=128,
    Timeout="180"
))

restApi = t.add_resource(api.RestApi(
    "restApi",
    Name="GDACK"
))

apiResource = t.add_resource(api.Resource(
    "apiResource",
    RestApiId=Ref(restApi),
    PathPart="{proxy+}",
    ParentId=GetAtt(restApi, "RootResourceId"),
))

apiMethod = t.add_resource(api.Method(
    "apiMethod",
    DependsOn='lambdaFunction',
    RestApiId=Ref(restApi),
    AuthorizationType="NONE",
    ResourceId=Ref(apiResource),
Ejemplo 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')
                                   ]))
                ]))
        ]))

lambda_function = template.add_resource(
    awslambda.Function("Lambda",
                       Code=awslambda.Code(
                           S3Bucket=Ref(param_lambda_source_bucket),
                           S3Key=Ref(param_lambda_file_name)),
                       Handler="lambda.lambda_handler",
                       MemorySize=128,
                       Role=GetAtt(lambda_role, "Arn"),
                       Runtime="python2.7",
                       Timeout=30))

api = template.add_resource(
    apigateway.RestApi("API", Description="My API", Name="MyAPI"))

api_lambda_permission = template.add_resource(
    awslambda.Permission("APILambdaPermission",
                         Action="lambda:InvokeFunction",
                         FunctionName=Ref(lambda_function),
                         Principal="apigateway.amazonaws.com",
                         SourceArn=Join("", [
                             "arn:aws:execute-api:",
                             Ref("AWS::Region"), ":",
                             Ref("AWS::AccountId"), ":",
                             Ref(api), "/*/GET/*"
                         ])))

api_first_resource = template.add_resource(
    apigateway.Resource("APIFirstResource",
Ejemplo n.º 5
0
from troposphere import Template, apigateway, Ref


def write_to_file(filename: str, data: str):
    with open(filename, 'w') as out:
        out.write(data)


template = Template()

template.set_description("JR-API gateway")

api = template.add_resource(
    apigateway.RestApi("API",
                       Description="Job Registry API via CloudFormation",
                       Name="CF-Rom-Job Registry API",
                       EndpointConfiguration=apigateway.EndpointConfiguration(
                           Types=["REGIONAL"])))

api_image_method = template.add_resource(
    apigateway.Method("auth",
                      ResourceId="auth",
                      ApiKeyRequired=False,
                      AuthorizationType="NONE",
                      HttpMethod="PUT",
                      RestApiId=Ref(api),
                      Integration=apigateway.Integration(
                          Uri="",
                          IntegrationResponses=[
                              apigateway.IntegrationResponse(
                                  "Default",
Ejemplo n.º 6
0
access_stack = t.add_parameter(Parameter(
    "AccessStack",
    Type="String",
    Description="Access stack name",
    Default="access"
))
lambda_stack = t.add_parameter(Parameter(
    "LambdaStack",
    Type="String",
    Description="Access stack name",
    Default="lambda"
))

api = t.add_resource(apigateway.RestApi(
    "Api",
    Name="ssh-ca-cfn",
    Body=schema
))

LAMBDA_ARN = ImportValue(
    Sub("${LambdaStack}-Bless")
)

account = t.add_resource(apigateway.Account(
    "Account",
    DependsOn=api.title,
    CloudWatchRoleArn=ImportValue(
        Sub("${AccessStack}-SshCaApiRole")
    )
))
Ejemplo n.º 7
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
Ejemplo n.º 8
0
    dynamodb.Table(
        'DevicesTable',
        TableName='Devices',
        KeySchema=[
            dynamodb.KeySchema(AttributeName='key', KeyType='HASH'),
        ],
        AttributeDefinitions=[
            dynamodb.AttributeDefinition(AttributeName='key',
                                         AttributeType='S'),
        ],
        BillingMode='PAY_PER_REQUEST',
    ))

restapi = template.add_resource(
    apigateway.RestApi('DevicesApi',
                       Name='DevicesApi',
                       Description='Devices API.',
                       BinaryMediaTypes=['application/vnd.pasbox.octets']))

authorizer_lambda = authorizer.generate(template)

authorizer_credentials = template.add_resource(
    iam.Role('DevicesApiAuthorizerCredentials',
             RoleName='DevicesApiAuthorizerCredentials',
             AssumeRolePolicyDocument=awacs.aws.PolicyDocument(
                 Version='2012-10-17',
                 Statement=[
                     awacs.aws.Statement(
                         Effect=awacs.aws.Allow,
                         Action=[awacs.sts.AssumeRole],
                         Principal=awacs.aws.Principal(
                             "Service", "apigateway.amazonaws.com"),
    "SourceBucket",
    Type="String",
    Description="Name of the bucket where Swagger file is stored"
))

param_ile_name = template.add_parameter(Parameter(
    "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),