Ejemplo n.º 1
0
    def test_acm(self):
        project_config = ProjectConfig(
            'tests/cloudformation/sample-project_acm.yaml', 'dev')
        config_parser = ConfigParser(project_config.config, 'my-stack-name')
        certificate_name = 'mycert'
        domain_name = 'helloworld.test.dsd.io'
        validation_domain = 'dsd.io'
        tags = [{
            'Key': 'Name',
            'Value': {
                'Fn::Join': ['', [{
                    'Ref': u'AWS::StackName'
                }, '-', u'acm']]
            }
        }, {
            'Key': 'test_key1',
            'Value': 'test_value_1'
        }, {
            'Key': 'test_key2',
            'Value': 'test_value_2'
        }]
        subject_alternative_names = [
            'goodbye.test.somewhere.io', 'hello_again.subdomain.dsd.io'
        ]

        # The main domain should use validation_domain,
        # 'goodbye.test.somewhere.io' should use the domain_validation_options
        # to validate on somewhere.io.
        # 'hello_again.subdomain.dsd.io' has no validation_options so should
        # default to the validation_domain
        domain_validation_options = [
            DomainValidationOption(DomainName=domain_name,
                                   ValidationDomain=validation_domain),
            DomainValidationOption(DomainName='goodbye.test.somewhere.io',
                                   ValidationDomain='somewhere.io'),
            DomainValidationOption(DomainName='hello_again.subdomain.dsd.io',
                                   ValidationDomain=validation_domain)
        ]
        ACMCertificate = Certificate(
            certificate_name,
            DomainName=domain_name,
            SubjectAlternativeNames=subject_alternative_names,
            DomainValidationOptions=domain_validation_options,
            Tags=tags)
        certificate_cfg = [
            config_parser._get_acm_certificate(certificate_name)
        ]
        expected = [ACMCertificate]
        compare(self._resources_to_dict(expected),
                self._resources_to_dict(certificate_cfg))
Ejemplo n.º 2
0
    def define_parameters_props(self) -> dict:
        """
        Determines the Properties to use for new ACM Certificate

        :return: properties dict
        :rtype: dict
        """
        tag_filter = re.compile(r"(^\*.)")
        validations = [
            DomainValidationOption(
                DomainName=domain_name,
                HostedZoneId=self.parameters["HostedZoneId"],
            )
            for domain_name in self.parameters["DomainNames"]
        ]
        props = {
            "DomainValidationOptions": validations,
            "DomainName": self.parameters["DomainNames"][0],
            "ValidationMethod": "DNS",
            "Tags": Tags(
                Name=tag_filter.sub("wildcard.", self.parameters["DomainNames"][0]),
                ZoneId=self.parameters["HostedZoneId"],
            ),
            "SubjectAlternativeNames": self.parameters["DomainNames"][1:],
        }
        return props
Ejemplo n.º 3
0
    def test_acm_non_alphanumeric(self):
        project_config = ProjectConfig(
            'tests/cloudformation/sample-project_acm.yaml', 'dev')
        config_parser = ConfigParser(project_config.config, 'my-stack-name')
        certificate_name = 'mycert-dev.something.io'
        parsed_certificate_name = 'mycertdevsomethingio'
        domain_name = 'helloworld.test.dsd.io'
        tags = [{
            'Key': 'Name',
            'Value': {
                'Fn::Join': ['', [{
                    'Ref': u'AWS::StackName'
                }, '-', u'acm']]
            }
        }]
        subject_alternative_names = []

        domain_validation_options = DomainValidationOption(
            DomainName=domain_name, ValidationDomain=domain_name)
        ACMCertificate = Certificate(
            parsed_certificate_name,
            DomainName=domain_name,
            SubjectAlternativeNames=subject_alternative_names,
            DomainValidationOptions=[domain_validation_options],
            Tags=tags)
        certificate_cfg = [
            config_parser._get_acm_certificate(certificate_name)
        ]
        expected = [ACMCertificate]
        compare(self._resources_to_dict(expected),
                self._resources_to_dict(certificate_cfg))
Ejemplo n.º 4
0
def initialize_acm_stack_template(cert_name):
    """
    Function to initialize a new certificate template
    :return:
    """
    tpl = build_template(
        "ACM Certificate",
        [
            VALIDATION_DOMAIN_ZONE_ID,
            VALIDATION_DOMAIN_NAME,
            CERT_VALIDATION_METHOD,
            CERT_CN,
            CERT_ALT_NAMES,
        ],
    )
    acm_conditions.add_all_conditions(tpl)
    cert = AcmCert(
        f"{cert_name}",
        template=tpl,
        DomainName=Ref(CERT_CN),
        SubjectAlternativeNames=If(acm_conditions.NO_ALT_NAMES_T,
                                   Ref(AWS_NO_VALUE), Ref(CERT_ALT_NAMES_T)),
        ValidationMethod=Ref(CERT_VALIDATION_METHOD),
        DomainValidationOptions=[
            If(
                acm_conditions.USE_ZONE_ID_T,
                DomainValidationOption(
                    DomainName=Ref(CERT_CN),
                    HostedZoneId=Ref(VALIDATION_DOMAIN_ZONE_ID),
                ),
                If(
                    acm_conditions.ACM_ZONE_NAME_IS_NONE_T,
                    DomainValidationOption(
                        DomainName=Ref(CERT_CN),
                        HostedZoneId=Ref(VALIDATION_DOMAIN_ZONE_ID),
                    ),
                    DomainValidationOption(
                        DomainName=Ref(CERT_CN),
                        ValidationDomain=Ref(VALIDATION_DOMAIN_NAME),
                    ),
                ),
            )
        ],
        Tags=Tags(Name=Ref(CERT_CN)),
    )
    tpl.add_output(ComposeXOutput(cert, [(CERT_CN, "", Ref(cert))]).outputs)
    return tpl
Ejemplo n.º 5
0
    def declare_domain(self, domain_name: str, hosted_zone_id: str,
                       stage_name: str) -> list[AWSObject]:
        """Declare a custom domain for one of the API stage.

        Note that when a custom domain is created then a certificate is automatically
        created for that domain.

        :param domain_name: domain name
        :param hosted_zone_id: hosted zone in which the domain belongs to
        :param stage_name: stage that should be associated with that domain
        :return: a list of AWSObject
        """
        result = []
        certificate_id = name_to_id(self.name + domain_name + "Certificate")
        certificate = Certificate(
            certificate_id,
            DomainName=domain_name,
            DomainValidationOptions=[
                DomainValidationOption(DomainName=domain_name,
                                       HostedZoneId=hosted_zone_id)
            ],
            ValidationMethod="DNS",
        )
        result.append(certificate)
        domain = apigatewayv2.DomainName(
            name_to_id(self.name + domain_name + "Domain"),
            DomainName=domain_name,
            DomainNameConfigurations=[
                apigatewayv2.DomainNameConfiguration(
                    CertificateArn=certificate.ref())
            ],
        )
        result.append(domain)
        result.append(
            apigatewayv2.ApiMapping(
                name_to_id(self.name + domain_name + "ApiMapping"),
                DomainName=domain.ref(),
                ApiId=self.ref,
                Stage=self.stage_ref(stage_name),
            ))
        result.append(
            route53.RecordSetType(
                name_to_id(self.name + domain_name + "DNS"),
                Name=domain_name,
                Type="A",
                HostedZoneId=hosted_zone_id,
                AliasTarget=route53.AliasTarget(
                    DNSName=GetAtt(
                        name_to_id(self.name + domain_name + "Domain"),
                        "RegionalDomainName",
                    ),
                    HostedZoneId=GetAtt(
                        name_to_id(self.name + domain_name + "Domain"),
                        "RegionalHostedZoneId",
                    ),
                    EvaluateTargetHealth=False,
                ),
            ))
        return result
Ejemplo n.º 6
0
def create_acm_certificate(stack, domain_name, alternate_names=[]):
    """Add ACM Certificate Resource."""
    return stack.stack.add_resource(Certificate(
        'mycert',
        DomainName='{0}'.format(domain_name),
        SubjectAlternativeNames=alternate_names,
        DomainValidationOptions=[
            DomainValidationOption(
                DomainName='{0}'.format(domain_name),
                ValidationDomain='{0}'.format(domain_name),
            ),
        ],
    ))
Ejemplo n.º 7
0
)
custom_app_certificate_arn_condition = "CustomAppCertArnCondition"
template.add_condition(custom_app_certificate_arn_condition, Not(Equals(Ref(custom_app_certificate_arn), "")))

stack_cert_condition = "StackCertificateCondition"
template.add_condition(stack_cert_condition, Not(Equals(Ref(certificate_validation_method), dont_create_value)))

cert_condition = "CertificateCondition"
template.add_condition(cert_condition, Or(
    Not(Equals(Ref(custom_app_certificate_arn), "")),
    Not(Equals(Ref(certificate_validation_method), dont_create_value))
))

application = If(custom_app_certificate_arn_condition,
                 Ref(custom_app_certificate_arn),
                 Ref(template.add_resource(
                     Certificate(
                         'Certificate',
                         Condition=stack_cert_condition,
                         DomainName=domain_name,
                         SubjectAlternativeNames=If(no_alt_domains, Ref("AWS::NoValue"), domain_name_alternates),
                         DomainValidationOptions=[
                             DomainValidationOption(
                                 DomainName=domain_name,
                                 ValidationDomain=domain_name,
                             ),
                         ],
                         ValidationMethod=Ref(certificate_validation_method)
                     )
                 )))
Ejemplo n.º 8
0
from troposphere import Template
from troposphere.certificatemanager import Certificate, DomainValidationOption

t = Template()

t.add_resource(
    Certificate(
        'mycert',
        DomainName='example.com',
        DomainValidationOptions=[
            DomainValidationOption(
                DomainName='example.com',
                ValidationDomain='example.com',
            ),
        ],
        Tags=[
            {
                'Key': 'tag-key',
                'Value': 'tag-value'
            },
        ],
    ))

print(t.to_json())
Ejemplo n.º 9
0
    # Currently, you can specify only certificates that are in the US East (N. Virginia) region.
    # http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distributionconfig-viewercertificate.html
    assets_custom_domain_and_us_east_1_condition = "AssetsCloudFrontDomainAndUsEast1Condition"
    template.add_condition(
        assets_custom_domain_and_us_east_1_condition,
        And(Not(Equals(Ref(assets_cloudfront_domain), "")),
            Equals(Ref(AWS_REGION), "us-east-1")))

    assets_certificate = template.add_resource(
        Certificate(
            'AssetsCertificate',
            Condition=assets_custom_domain_and_us_east_1_condition,
            DomainName=Ref(assets_cloudfront_domain),
            DomainValidationOptions=[
                DomainValidationOption(
                    DomainName=Ref(assets_cloudfront_domain),
                    ValidationDomain=Ref(assets_cloudfront_domain),
                ),
            ],
        ))

    assets_certificate_arn = template.add_parameter(
        Parameter(
            "AssetsCloudFrontCertArn",
            Description=
            "If (1) you specified a custom static media domain, (2) your stack is NOT in the us-east-1 "
            "region, and (3) you wish to serve static media over HTTPS, you must manually create an "
            "ACM certificate in the us-east-1 region and provide its ARN here.",
            Type="String",
        ),
        group="Static Media",
        label="CloudFront SSL Certificate ARN",
from troposphere import Template
from troposphere.certificatemanager import Certificate, DomainValidationOption

t = Template()

t.add_resource(
    Certificate(
        "mycert",
        DomainName="example.com",
        DomainValidationOptions=[
            DomainValidationOption(
                DomainName="example.com",
                ValidationDomain="example.com",
            ),
        ],
        Tags=[
            {
                "Key": "tag-key",
                "Value": "tag-value"
            },
        ],
    ))

print(t.to_json())
Ejemplo n.º 11
0
domain_name = template.add_parameter(
    Parameter(
        'DomainName',
        Type=constants.STRING,
        Default='videos.spunt.be',
    ))

cloudfront_certificate = template.add_resource(
    Certificate(
        "CloudFrontCertificate",
        DomainName=Ref(domain_name),
        DomainValidationOptions=[
            DomainValidationOption(
                DomainName=Ref(domain_name),
                ValidationDomain=ImportValue(
                    Join('-', [Ref(dns_stack), 'HostedZoneName'])),
            )
        ],
        ValidationMethod='DNS',
    ))

video_cdn = template.add_resource(
    Distribution(
        "VideoDistribution",
        DistributionConfig=DistributionConfig(
            Aliases=[Ref(domain_name)],
            Comment=Ref(AWS_STACK_NAME),
            DefaultCacheBehavior=DefaultCacheBehavior(
                TargetOriginId='S3',
                ViewerProtocolPolicy='redirect-to-https',
Ejemplo n.º 12
0
        Type=constants.STRING,
        Default='rob-kenis-dot-com-dns',
        Description=
        'Name of the CloudFormation stack that holds the HostedZone',
    ))

cloudfront_certificate = template.add_resource(
    Certificate(
        "CloudFrontCertificate",
        DomainName='robkenis.com',
        SubjectAlternativeNames=['www.robkenis.com'],
        ValidationMethod='DNS',
        DomainValidationOptions=[
            DomainValidationOption(
                DomainName='robkenis.com',
                HostedZoneId=ImportValue(
                    Join('-', [Ref(dns_stack), 'HostedZoneId'])),
            ),
            DomainValidationOption(
                DomainName='www.robkenis.com',
                HostedZoneId=ImportValue(
                    Join('-', [Ref(dns_stack), 'HostedZoneId'])),
            ),
        ],
        Tags=Tags({'Name': Ref(AWS_STACK_NAME)}),
    ))

s3_website_origin = template.add_resource(
    Bucket(
        'WebsiteOrigin',
        AccessControl='Private',
Ejemplo n.º 13
0
    default_ttl = 86400,

    # If an alt_sub domain is not specified use empty string
    if domain_info['alt_sub'] != '':
        alternate_name = '{}.{}'.format(domain_info['alt_sub'], src_domain)
    else:
        alternate_name = ''

    # Provision certificate for CDN
    cdnCertificate = t.add_resource(
        Certificate('cdnCertificate{}'.format(src_domain.replace('.', '0')),
                    DomainName=cdn_domain,
                    DependsOn=redirectBucket,
                    SubjectAlternativeNames=[alternate_name],
                    DomainValidationOptions=[
                        DomainValidationOption(DomainName=cdn_domain,
                                               ValidationDomain=dns_domain)
                    ],
                    ValidationMethod='DNS',
                    Tags=DefaultTags +
                    Tags(Name='{}-{}'.format(env_l, app_group_l))))

    # Provision the CDN Origin
    cdnOrigin = cf.Origin(Id='{}-{}-{}'.format(env_l, app_group_l, src_domain),
                          DomainName=Select(
                              1,
                              Split('//', GetAtt(redirectBucket,
                                                 'WebsiteURL'))),
                          CustomOriginConfig=cf.CustomOriginConfig(
                              HTTPPort=80,
                              HTTPSPort=443,
                              OriginProtocolPolicy='http-only',
Ejemplo n.º 14
0
zone_set_cond = t.add_condition(
    'zoneIdSet',
    Not(Equals(Ref(zone_id), ''))
)

#############
# Resources
#############

# SSL cert for CloudFront
ssl_certificate = t.add_resource(Certificate(
    'myCert',
    DomainName              = Ref(domain_name),
    DomainValidationOptions = [
        DomainValidationOption(
            DomainName          = Ref(domain_name),
            ValidationDomain    = Ref(zone_apex),
        ),
    ],
))

s3_bucket = t.add_resource(Bucket('myBucket'))

bucket_policy = t.add_resource(BucketPolicy(
    'myBucketPolicy',
    Bucket          = Ref(s3_bucket),
    PolicyDocument  = {
        'Version'   : '2012-10-17',
        'Id'        : 'PolicyForCloudFrontPrivateContent',
        'Statement' : [
            {
               'Sid'        : ' Grant a CloudFront Origin Identity access to support private content',