Search code examples
pythonamazon-web-servicesaws-cdkinfrastructure-as-code

'SiteCertificate' object has no attribute 'certificate_arn' with AWS CDK


I'm trying to move a CloudFormation project to AWS CDK. I'm starting with the frontend which is a static site using a CloudFront distribution in front of an S3 bucket with a Certificate Manager certificate.

Here are the various components I'm using to build this stack:

Root

from aws_cdk import core

from cert import SiteCertificate
from hosted_zone import HostedZone
from static_site import StaticSite


class AwscdkStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.hosted_zone = HostedZone(self, "HostedZone")

        self.certificate = SiteCertificate(self, "SiteCert")

        self.static_site = StaticSite(
            self, 'StaticSite',
            hosted_zone=self.hosted_zone,
            certificate=self.certificate
        )

Hosted Zone

import os

from aws_cdk import (
    core,
    aws_route53 as route53
)


class HostedZone(core.Construct):

    def __init__(self, scope: core.Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self.hosted_zone = route53.HostedZone.from_hosted_zone_attributes(
            self, "hosted_zone",
            hosted_zone_id=os.environ.get("HOSTED_ZONE_ID", "ABC123"),
            zone_name=os.environ.get("DOMAIN_NAME", "mysite.com")
        )

Certificate

import os

from aws_cdk import (
    core,
    aws_certificatemanager as acm,
)

class SiteCertificate(core.Construct):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        cert = acm.Certificate(
            self, "SiteCertificate",
            domain_name=f"*.{os.environ.get('DOMAIN_NAME', 'mysite.com')}"
        )

Static Site

This contains the S3 bucket, policy and CloudFront distibution (I may want to break these out into different files)

import os

from aws_cdk import (
    aws_certificatemanager as acm,
    aws_s3 as s3,
    aws_cloudfront as cloudfront,
    aws_route53 as route53,
    aws_iam as iam,
    core
)


class StaticSite(core.Construct):

    def __init__(
        self,
        scope: core.Construct,
        id: str,
        hosted_zone: route53.IHostedZone,
        certificate: acm.ICertificate,
        **kwargs
    ) -> None:
        super().__init__(scope, id, **kwargs)

        self.static_site_bucket = s3.Bucket(
            self, "StaticSiteBucket",
            access_control=s3.BucketAccessControl.PUBLIC_READ,
            bucket_name=os.environ.get("DOMAIN_NAME", "mysite.com"),
            removal_policy=core.RemovalPolicy.DESTROY,
        )

        self.policy_statement = iam.PolicyStatement(
            actions=["s3:GetObject"],
            resources=[f"{self.static_site_bucket.bucket_arn}/*"]
        )

        self.policy_statement.add_any_principal()

        self.static_site_policy_document = iam.PolicyDocument(
            statements=[self.policy_statement]
        )

        self.static_site_bucket.add_to_resource_policy(
            self.policy_statement
        )

        self.distribution = cloudfront.CloudFrontWebDistribution(
            self, "CloudFrontDistribution",
            origin_configs=[
                cloudfront.SourceConfiguration(
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=self.static_site_bucket
                    ),
                    behaviors=[cloudfront.Behavior(is_default_behavior=True)]
                )
            ],
            alias_configuration=cloudfront.AliasConfiguration(
                acm_cert_ref=certificate.certificate_arn,
                names=[
                    os.environ.get("DOMAIN_NAME", "mysite.com"),
                    f"*.{os.environ.get('DOMAIN_NAME', 'mysite.com')}"]
            ),
            error_configurations=[
                {
                    "errorCode": 403,
                    "errorCachingMinTtl": 0,
                    "responseCode": 200,
                    "responsePagePath": "/index.html"
                },
                {
                    "errorCode": 404,
                    "errorCachingMinTtl": 0,
                    "responseCode": 200,
                    "responsePagePath": "/index.html"
                }
            ]
        )

I haven't deployed anything yet, I'm only testing this locally with cdk synth. I have been running cdk synth with each addition I make in my CDK files and the CloudFormation output has been similar to what I have in the CloudFormation templates that I am currently using to deploy the project. When I run cdk sythn, I get the following error:

AttributeError: 'SiteCertificate' object has no attribute 'certificate_arn'

Am I using the right constructs here? Does the certificate need to exist before I can access it's ARN? I have tried using DnsValidatedCertificate but I get the same error. I also noticed that this method is experimental, so I'm not sure if that has anything to do with why I would be seeing this error.


Solution

  • This looks like you're missing a property definition on SiteCertificate

            self.certificate = SiteCertificate(self, "SiteCert")
    
            self.static_site = StaticSite(
                self, 'StaticSite',
                hosted_zone=self.hosted_zone,
                certificate=self.certificate
            )
    

    inside StaticSite you reference certificate.certificate_arn but SiteCertificate doesn't have that property defined.

    class SiteCertificate(core.Construct):
    
        def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
            super().__init__(scope, id, **kwargs)
    
            cert = acm.Certificate(
                self, "SiteCertificate",
                domain_name=f"*.{os.environ.get('DOMAIN_NAME', 'mysite.com')}"
            )
            // Add this
            self.certificate_arn = cert.certificate_arn
    

    Or make your SiteCertificate inherit from acm.Ceritificate

    class SiteCertificate(acm.Certificate):
    
        def __init__(self, scope: core.Construct) -> None:
            super().__init__(scope, "SiteCertificate",
                domain_name=f"*.{os.environ.get('DOMAIN_NAME', 'mysite.com')}")
    

    I am not a python expert so I may be missing something.