How to Clone a CloudFront Distribution in Minutes

How to Clone a CloudFront Distribution in Minutes

For the past few months, we have been creating a new CloudFront distribution for each one of our customers with around 13 or more behaviors. This process can be quite tedious. Doing this task from GUI can become an exhausting task where you need to create these behaviors from scratch every time, which is not only boring but also difficult when it comes down to remembering all that needs to be done in order to get your distributions up-and-running. In this article, we are going to see how you can clone an existing distribution in a couple of minutes and enjoy doing it :)

doit

Install AWS CLI

The AWS CLI is a powerful tool for managing your cloud computing resources, and it makes life so much easier to do from the command line.

If you haven't done it already, make sure you follow AWS official docs to install AWS CLI. docs.aws.amazon.com/cli/latest/userguide/in..

Export existing distribution configs

First, let's create new directory to save configs there

mkdir aws-cloudfront-configs && cd aws-cloudfront-configs

Edit configuration

get-distribution-config

aws cloudfront get-distribution-config --id [ID-OF-YOUR-DISTRIBUTION] --output json > distributionConfigs.json

If you have multiple profiles, make sure you use --profile in the command.

Edit the config file

Remove ETag and DistributionConfig and it's closing curly brackets. Following should be removed.

    "ETag": "XXXXXXXXX",
    "DistributionConfig": {

CallerReference

Change CallerReference to a unique number.

Change Aliases

Change Aliases data to reflect new site information. If you don't have any Alias for new site yet, remove the section. This part should be removed

        "Aliases": {
            "Quantity": 1,
            "Items": [
                "oldDOmain"
            ]
        },

Replace old domain with new one

Now for DefaultCacheBehavior, Origins and CacheBehaviors make sure to replace old domain with new one

ViewerCertificate

If you have generated SSL cert in ACM, replace what you have under ViewerCertificate with new certificate information if not remove the ViewerCertificate section completely.

        "ViewerCertificate": {
            "ACMCertificateArn": "XXXX",
            "SSLSupportMethod": "XXXX",
            "MinimumProtocolVersion": "TLSv1.2_2019",
            "Certificate": "XXXX",
            "CertificateSource": "acm"
        },

Create new distribution

Make sure you are in the folder you created the distributionConfigs.json file, create a copy of it for example myNewSite.json and run the following command.

aws cloudfront create-distribution --distribution-config file://myNewSite.json

Don't forget to add file:// before the filename. If you don't do that, get an error.