示例#1
0
def create_method_config(request, responses):
    """
    Creates a method config object, stitching together the request and reponses that are passed in
    :param request: a request config object.
    :param responses: a list of response config objects
    :return: a method config object
    """

    return ApiGatewayMethodConfig(method_name=methodname,
                                  lambda_unit=lambda_title,
                                  request_config=request,
                                  response_config=responses,
                                  httpmethod=httpmethod,
                                  authorizationtype=authorizationtype)
def main():
    template = Template()
    api_name = 'apigw1'
    method_name = 'login'
    lambda_title = 'MyLambda'
    http_method = 'POST'
    authorization_type = 'NONE'

    request_template = {'application/json': """{ "username": $input.json('$.username')}"""}
    request_parameters = {'method.request.header.Origin': "$input.params('Origin')"}
    response_template = {'application/json': ''}
    response_parameters = {'method.response.header.Set-COokie': 'integration.response.body.TESTVALUE'}
    response_models = {'application/json': 'Empty'}
    status_code = '200'
    selection_pattern = ''
    request_config = ApiGatewayRequestConfig(templates=request_template,
                                             parameters=request_parameters)
    response_config1 = ApiGatewayResponseConfig(templates=response_template,
                                                parameters=response_parameters,
                                                statuscode=status_code,
                                                models=response_models,
                                                selectionpattern=selection_pattern)
    status_code = '403'
    selection_pattern = 'Invalid.*'
    response_config2 = ApiGatewayResponseConfig(templates=response_template,
                                                parameters=response_parameters,
                                                statuscode=status_code,
                                                models=response_models,
                                                selectionpattern=selection_pattern)

    method_config = ApiGatewayMethodConfig(method_name=method_name,
                                           lambda_unit=lambda_title,
                                           request_config=request_config,
                                           response_config=[response_config1, response_config2],
                                           httpmethod=http_method,
                                           authorizationtype=authorization_type)

    ApiGatewayLeaf(leaf_title=api_name,
                   template=template,
                   method_config=[method_config],
                   tree_name='tree')

    print(template.to_json(indent=2, separators=(',', ': ')))
示例#3
0
def create_stack(nat_highly_available=False):
    """
    Helper function to create a stack with default values
    :return new stack
    """
    global userdata, availability_zones, keypair, instance_type, code_deploy_service_role, vpc_cidr, \
        public_cidr, instance_port, loadbalancer_port, instance_protocol, loadbalancer_protocol, minsize, maxsize, \
        elb_health_check, home_cidrs, nat_image_id, jump_image_id, health_check_grace_period, health_check_type, \
        unit_image_id, db_instance_type, db_engine, db_port, owner_emails, db_backup_window, \
        db_backup_retention, db_maintenance_window, db_storage_type, block_devices_config, healthy_threshold, \
        unhealthy_threshold, interval, timeout, elb_listeners_config, sticky_app_cookies

    stack = Stack(
        code_deploy_service_role=code_deploy_service_role,
        keypair=keypair,
        availability_zones=availability_zones,
        vpc_cidr=vpc_cidr,
        public_cidr=public_cidr,
        home_cidrs=home_cidrs,
        jump_image_id=jump_image_id,
        jump_instance_type=instance_type,
        nat_image_id=nat_image_id,
        nat_instance_type=instance_type,
        public_hosted_zone_name=None,
        private_hosted_zone_name='priavte.lan.',
        iam_instance_profile_arn=None,
        owner_emails=owner_emails,
        nat_highly_available=nat_highly_available,
        ec2_scheduled_shutdown=False,
        zd_autoscaling_units=[{
            'unit_title':
            'zdapp1',
            'elb_config':
            ElbConfig(elb_listeners_config=elb_listeners_config,
                      elb_health_check=elb_health_check,
                      elb_log_bucket=None,
                      public_unit=True,
                      ssl_certificate_id=None,
                      healthy_threshold=healthy_threshold,
                      unhealthy_threshold=unhealthy_threshold,
                      interval=interval,
                      timeout=timeout),
            'blue_asg_config':
            AsgConfig(minsize=minsize,
                      maxsize=maxsize,
                      image_id=unit_image_id,
                      instance_type=instance_type,
                      health_check_grace_period=health_check_grace_period,
                      health_check_type=health_check_type,
                      userdata=userdata,
                      iam_instance_profile_arn=None,
                      block_devices_config=block_devices_config,
                      simple_scaling_policy_config=None,
                      ec2_scheduled_shutdown=None),
            'green_asg_config':
            AsgConfig(minsize=minsize,
                      maxsize=maxsize,
                      image_id=unit_image_id,
                      instance_type=instance_type,
                      health_check_grace_period=health_check_grace_period,
                      health_check_type=health_check_type,
                      userdata=userdata,
                      iam_instance_profile_arn=None,
                      block_devices_config=block_devices_config,
                      simple_scaling_policy_config=None,
                      ec2_scheduled_shutdown=None),
            'dependencies': ['app2:5432', 'db1:80'],
        }],
        autoscaling_units=[{
            'unit_title':
            'app1',
            'elb_config':
            ElbConfig(elb_listeners_config=elb_listeners_config,
                      elb_health_check=elb_health_check,
                      elb_log_bucket=None,
                      public_unit=True,
                      ssl_certificate_id=None,
                      healthy_threshold=healthy_threshold,
                      unhealthy_threshold=unhealthy_threshold,
                      interval=interval,
                      timeout=timeout),
            'asg_config':
            AsgConfig(minsize=minsize,
                      maxsize=maxsize,
                      image_id=unit_image_id,
                      instance_type=instance_type,
                      health_check_grace_period=health_check_grace_period,
                      health_check_type=health_check_type,
                      userdata=userdata,
                      iam_instance_profile_arn=None,
                      block_devices_config=block_devices_config,
                      simple_scaling_policy_config=None,
                      ec2_scheduled_shutdown=None),
            'dependencies': ['app2:80', 'db1:5432'],
        }, {
            'unit_title':
            'app2',
            'elb_config':
            ElbConfig(elb_listeners_config=elb_listeners_config,
                      elb_health_check=elb_health_check,
                      elb_log_bucket=None,
                      public_unit=True,
                      ssl_certificate_id=None,
                      healthy_threshold=healthy_threshold,
                      unhealthy_threshold=unhealthy_threshold,
                      interval=interval,
                      timeout=timeout),
            'asg_config':
            AsgConfig(minsize=minsize,
                      maxsize=maxsize,
                      image_id=unit_image_id,
                      instance_type=instance_type,
                      health_check_grace_period=health_check_grace_period,
                      health_check_type=health_check_type,
                      userdata=userdata,
                      iam_instance_profile_arn=None,
                      block_devices_config=block_devices_config,
                      simple_scaling_policy_config=None,
                      ec2_scheduled_shutdown=None),
            'dependencies': []
        }],
        database_units=[{
            'unit_title':
            'db1',
            'database_config':
            DatabaseConfig(db_instance_type=db_instance_type,
                           db_engine=db_engine,
                           db_port=db_port,
                           db_hdd_size=db_hdd_size,
                           db_snapshot_id=None,
                           db_name='MyDb',
                           db_backup_window=db_backup_window,
                           db_backup_retention=db_backup_retention,
                           db_maintenance_window=db_maintenance_window,
                           db_storage_type=db_storage_type)
        }],
        cf_distribution_units=[{
            'unit_title':
            'cfdist1',
            'cf_origins_config': [
                CFOriginsConfig(
                    domain_name='amazonia-elb-bucket.s3.amazonaws.com',
                    origin_id='S3-amazonia-elb-bucket',
                    origin_path='',
                    custom_headers={
                        'Origin': 'http://www.domain.com',
                        'Accept': 'True'
                    },
                    origin_policy={
                        'is_s3': True,
                        'origin_access_identity': 'originaccessid1'
                    }),
                CFOriginsConfig(domain_name='app1',
                                origin_id='www-elb',
                                origin_path='/path',
                                custom_headers={},
                                origin_policy={
                                    'is_s3':
                                    False,
                                    'origin_protocol_policy':
                                    'https-only',
                                    'http_port':
                                    80,
                                    'https_port':
                                    443,
                                    'origin_ssl_protocols':
                                    ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
                                }),
                CFOriginsConfig(domain_name='validYamlTestAPIGW',
                                origin_id='www-elb2',
                                origin_path='/path',
                                custom_headers={},
                                origin_policy={
                                    'is_s3':
                                    False,
                                    'origin_protocol_policy':
                                    'https-only',
                                    'http_port':
                                    80,
                                    'https_port':
                                    443,
                                    'origin_ssl_protocols':
                                    ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
                                })
            ],
            'cf_distribution_config':
            CFDistributionConfig(
                aliases=['www.test-stack.gadevs.ga', 'test-stack.gadevs.ga'],
                comment='SysTestCFDistribution',
                default_root_object='index.html',
                enabled=True,
                price_class='PriceClass_All',
                error_page_path='index.html',
                acm_cert_arn='arn.acm.certificate',
                minimum_protocol_version='TLSv1',
                ssl_support_method='sni-only'),
            'cf_cache_behavior_config': [
                CFCacheBehaviorConfig(
                    is_default=True,
                    path_pattern='/index.html',
                    allowed_methods=['GET', 'HEAD'],
                    cached_methods=['GET', 'HEAD'],
                    target_origin_id='S3-bucket-id',
                    forward_cookies='all',
                    forwarded_headers=['Accept', 'Set-Cookie'],
                    viewer_protocol_policy='allow-all',
                    min_ttl=0,
                    default_ttl=0,
                    max_ttl=0,
                    trusted_signers=['self'],
                    query_string='False'),
                CFCacheBehaviorConfig(
                    is_default=False,
                    path_pattern='/login.js',
                    allowed_methods=[
                        'GET', 'POST', 'HEAD', 'DELETE', 'OPTIONS', 'PATCH',
                        'PUT'
                    ],
                    cached_methods=['GET', 'HEAD'],
                    target_origin_id='www-origin',
                    forward_cookies='all',
                    forwarded_headers=['Accept', 'Set-Cookie'],
                    viewer_protocol_policy='https-only',
                    min_ttl=0,
                    default_ttl=0,
                    max_ttl=0,
                    trusted_signers=['self'],
                    query_string='True')
            ]
        }],
        api_gateway_units=[{
            'unit_title':
            'validYamlTestAPIGW',
            'method_config': [
                ApiGatewayMethodConfig(
                    method_name='login',
                    lambda_unit='validYamlTestLambda',
                    httpmethod='POST',
                    authorizationtype='NONE',
                    request_config=ApiGatewayRequestConfig(
                        templates={'application/json': ''},
                        parameters={'somemapping': 'somefield'}),
                    response_config=[
                        ApiGatewayResponseConfig(
                            templates={'application/json': ''},
                            parameters={'somemapping': 'somefield'},
                            statuscode='200',
                            models={'application/json': 'Empty'},
                            selectionpattern='')
                    ])
            ]
        }],
        lambda_units=[{
            'unit_title':
            'validYamlTestLambda',
            'dependencies': ['db1:5432'],
            'lambda_config':
            LambdaConfig(lambda_s3_bucket='bucket_name',
                         lambda_s3_key='key_name',
                         lambda_description='blah',
                         lambda_function_name='my_function',
                         lambda_handler='main',
                         lambda_memory_size=128,
                         lambda_role_arn='test_arn',
                         lambda_runtime='python2.7',
                         lambda_timeout=1,
                         lambda_schedule='cron(0/5 * * * ? *)')
        }])
    return stack
def main():
    network_config, template = get_network_config()

    userdata = """
    #cloud-config
    repo_update: true
    repo_upgrade: all

    packages:
     - httpd

    runcmd:
     - service httpd start
        """
    elb_listeners_config = [
        ElbListenersConfig(
            instance_port='80',
            loadbalancer_port='80',
            loadbalancer_protocol='HTTP',
            instance_protocol='HTTP',
            sticky_app_cookie=None
        )
    ]

    elb_config = ElbConfig(
        elb_health_check='TCP:80',
        elb_log_bucket=None,
        public_unit=True,
        ssl_certificate_id=None,
        healthy_threshold=10,
        unhealthy_threshold=2,
        interval=300,
        timeout=30,
        owner='*****@*****.**',
        elb_listeners_config=elb_listeners_config
    )

    block_devices_config = [BlockDevicesConfig(device_name='/dev/xvda',
                                               ebs_volume_size='15',
                                               ebs_volume_type='gp2',
                                               ebs_encrypted=False,
                                               ebs_snapshot_id=None,
                                               virtual_name=False)
                            ]

    asg_config = AsgConfig(
        minsize=1,
        maxsize=2,
        health_check_grace_period=300,
        health_check_type='ELB',
        image_id='ami-dc361ebf',
        instance_type='t2.nano',
        userdata=userdata,
        iam_instance_profile_arn=None,
        block_devices_config=block_devices_config,
        simple_scaling_policy_config=None,
        ec2_scheduled_shutdown=None,
        pausetime='10',
        owner='*****@*****.**'
    )

    app_name = 'app1'

    AutoscalingUnit(
        unit_title=app_name,
        template=template,
        dependencies=[],
        stack_config=network_config,
        elb_config=elb_config,
        asg_config=asg_config,
        ec2_scheduled_shutdown=None
    )

    apiname = 'apigw1'
    methodname = 'login'
    lambda_title = 'MyLambda'
    httpmethod = 'POST'
    authorizationtype = 'NONE'

    request_template = {'application/json': """{ "username": $input.json('$.username')}"""}
    request_parameters = {'method.request.header.Origin': "$input.params('Origin')"}
    response_template = {'application/json': ''}
    response_parameters = {'method.response.header.Set-COokie': 'integration.response.body.TESTVALUE'}
    response_models = {'application/json': 'Empty'}
    statuscode = '200'
    selectionpattern = ''
    request_config = ApiGatewayRequestConfig(templates=request_template,
                                             parameters=request_parameters)
    response_config1 = ApiGatewayResponseConfig(templates=response_template,
                                                parameters=response_parameters,
                                                statuscode=statuscode,
                                                models=response_models,
                                                selectionpattern=selectionpattern)
    statuscode = '403'
    selectionpattern = 'Invalid.*'
    response_config2 = ApiGatewayResponseConfig(templates=response_template,
                                                parameters=response_parameters,
                                                statuscode=statuscode,
                                                models=response_models,
                                                selectionpattern=selectionpattern)

    method_config = ApiGatewayMethodConfig(method_name=methodname,
                                           lambda_unit=lambda_title,
                                           request_config=request_config,
                                           response_config=[response_config1, response_config2],
                                           httpmethod=httpmethod,
                                           authorizationtype=authorizationtype)
    lambda_config = LambdaConfig(
        lambda_s3_bucket='smallest-bucket-in-history',
        lambda_s3_key='test_lambda.zip',
        lambda_description='test function',
        lambda_function_name='test_lambda',
        lambda_handler='test_lambda.lambda_handler',
        lambda_memory_size=128,
        lambda_role_arn='arn:aws:iam::123456789:role/lambda_basic_vpc_execution_with_s3',
        lambda_runtime='python2.7',
        lambda_timeout=1,
        lambda_schedule='rate(5 minutes)'
    )

    LambdaUnit(
        unit_title=lambda_title,
        template=template,
        dependencies=[],
        stack_config=network_config,
        lambda_config=lambda_config
    )

    ApiGatewayUnit(unit_title=apiname,
                   template=template,
                   method_config=[method_config],
                   stack_config=network_config)

    origins = [
        CFOriginsConfig(
            domain_name=app_name,
            origin_id=app_name,
            origin_path='',
            custom_headers=[],
            origin_policy={
                'is_s3': False,
                'origin_protocol_policy': 'http-only',
                'http_port': 80,
                'https_port': 443,
                'origin_ssl_protocols': ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
            }
        ),
        CFOriginsConfig(
            domain_name=apiname,
            origin_id=apiname,
            origin_path='/amz_deploy',
            custom_headers=[],
            origin_policy={
                'is_s3': False,
                'origin_protocol_policy': 'https-only',
                'http_port': 80,
                'https_port': 443,
                'origin_ssl_protocols': ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
            }
        )
    ]

    cache_behavior = [
        CFCacheBehaviorConfig(
            is_default=True,
            path_pattern='',
            allowed_methods=['GET', 'HEAD'],
            cached_methods=['GET', 'HEAD'],
            target_origin_id='app1',
            forward_cookies='all',
            forwarded_headers=[],
            viewer_protocol_policy='allow-all',
            min_ttl=0,
            default_ttl=0,
            max_ttl=0,
            trusted_signers=[],
            query_string=True
        ),
        CFCacheBehaviorConfig(
            is_default=False,
            path_pattern='/login',
            allowed_methods=['GET', 'POST', 'HEAD', 'DELETE', 'OPTIONS', 'PATCH', 'PUT'],
            cached_methods=['GET', 'HEAD'],
            target_origin_id='apigw1',
            forward_cookies='all',
            forwarded_headers=['Accept',
                               'Accept-Charset',
                               'Accept-Datetime',
                               'Accept-Language',
                               'Authorization',
                               'Content-Type',
                               'Origin',
                               'Referer',
                               'Set-Cookie'],
            viewer_protocol_policy='https-only',
            min_ttl=0,
            default_ttl=0,
            max_ttl=0,
            trusted_signers=[],
            query_string=False
        ),
    ]

    distribution_config = CFDistributionConfig(
        aliases=[],
        comment='SysTestCFDistribution',
        default_root_object='',
        enabled=True,
        price_class='PriceClass_All',
        error_page_path='',
        acm_cert_arn=None,
        minimum_protocol_version='TLSv1',
        ssl_support_method='sni-only'
    )

    CFDistributionUnit(unit_title='cfdist',
                       template=template,
                       stack_config=network_config,
                       cf_origins_config=origins,
                       cf_cache_behavior_config=cache_behavior,
                       cf_distribution_config=distribution_config)

    print(template.to_json(indent=2, separators=(',', ': ')))
def main():
    network_config, template = get_network_config()

    apiname = 'apigw1'
    methodname = 'login'
    lambda_title = 'MyLambda'
    httpmethod = 'POST'
    authorizationtype = 'NONE'

    request_template = {
        'application/json': """{ "username": $input.json('$.username')}"""
    }
    request_parameters = {
        'method.request.header.Origin': "$input.params('Origin')"
    }
    response_template = {'application/json': ''}
    response_parameters = {
        'method.response.header.Set-COokie':
        'integration.response.body.TESTVALUE'
    }
    response_models = {'application/json': 'Empty'}
    statuscode = '200'
    selectionpattern = ''
    request_config = ApiGatewayRequestConfig(templates=request_template,
                                             parameters=request_parameters)
    response_config1 = ApiGatewayResponseConfig(
        templates=response_template,
        parameters=response_parameters,
        statuscode=statuscode,
        models=response_models,
        selectionpattern=selectionpattern)
    statuscode = '403'
    selectionpattern = 'Invalid.*'
    response_config2 = ApiGatewayResponseConfig(
        templates=response_template,
        parameters=response_parameters,
        statuscode=statuscode,
        models=response_models,
        selectionpattern=selectionpattern)

    method_config = ApiGatewayMethodConfig(
        method_name=methodname,
        lambda_unit=lambda_title,
        request_config=request_config,
        response_config=[response_config1, response_config2],
        httpmethod=httpmethod,
        authorizationtype=authorizationtype)

    lambda_config = LambdaConfig(
        lambda_s3_bucket='smallest-bucket-in-history',
        lambda_s3_key='test_lambda.zip',
        lambda_description='test function',
        lambda_function_name='test_lambda',
        lambda_handler='test_lambda.lambda_handler',
        lambda_memory_size=128,
        lambda_role_arn=
        'arn:aws:iam::123456789:role/lambda_basic_vpc_execution_with_s3',
        lambda_runtime='python2.7',
        lambda_timeout=1,
        lambda_schedule='rate(5 minutes)')

    LambdaUnit(unit_title=lambda_title,
               template=template,
               dependencies=[],
               stack_config=network_config,
               lambda_config=lambda_config)

    ApiGatewayUnit(unit_title=apiname,
                   template=template,
                   method_config=[method_config],
                   stack_config=network_config)

    print(template.to_json(indent=2, separators=(',', ': ')))