> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloudfront use cdn remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        The misconfiguration is that the web application is not using a Content Delivery Network (CDN) which can lead to slower load times and higher latency for users. Here are the step-by-step instructions to remediate this issue for AWS using the AWS console:

        1. Log in to the AWS Management Console.
        2. Navigate to the Amazon CloudFront service.
        3. Click on the "Create Distribution" button.
        4. Select the "Web" option for the type of distribution.
        5. In the "Origin Domain Name" field, enter the domain name of your web application.
        6. In the "Origin Protocol Policy" field, select "HTTPS Only" to ensure that all traffic to your web application is encrypted.
        7. In the "Viewer Protocol Policy" field, select "Redirect HTTP to HTTPS" to ensure that all traffic is encrypted.
        8. In the "Allowed HTTP Methods" field, select "GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE" to allow all necessary HTTP methods.
        9. In the "Price Class" field, select the appropriate price class for your needs.
        10. In the "Alternate Domain Names (CNAMEs)" field, enter any alternate domain names that you want to use for your web application.
        11. In the "Default Root Object" field, enter the name of the default file that should be served when a user accesses your web application.
        12. Click on the "Create Distribution" button to create your CDN distribution.

        Once you have completed these steps, your web application will be using a CDN which will improve load times and reduce latency for your users.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Web Applications Should Use CDNs" for AWS using AWS CLI, follow these steps:

        1. Login to AWS CLI using your AWS account credentials.

        2. Identify the web application that needs to be configured with CDN.

        3. Create an S3 bucket that will store the static content of the web application. Use the following AWS CLI command to create an S3 bucket:

        ```
        aws s3api create-bucket --bucket <bucket-name> --region <region>
        ```

        Replace `<bucket-name>` with a unique name for your S3 bucket and `<region>` with the region where you want to create the bucket.

        4. Upload the static content of the web application to the S3 bucket. Use the following AWS CLI command to upload the files:

        ```
        aws s3 sync <local-path> s3://<bucket-name> --acl public-read
        ```

        Replace `<local-path>` with the local path of the static files and `<bucket-name>` with the name of the S3 bucket you created in step 3.

        5. Create a CloudFront distribution for the S3 bucket. Use the following AWS CLI command to create a CloudFront distribution:

        ```
        aws cloudfront create-distribution --origin-domain-name <bucket-name>.s3.amazonaws.com --default-root-object index.html
        ```

        Replace `<bucket-name>` with the name of the S3 bucket you created in step 3.

        6. Update the DNS settings of the web application to point to the CloudFront distribution. Use the following AWS CLI command to get the CloudFront distribution domain name:

        ```
        aws cloudfront get-distribution --id <distribution-id> --query "Distribution.DomainName" --output text
        ```

        Replace `<distribution-id>` with the ID of the CloudFront distribution you created in step 5.

        7. Update the DNS settings of the web application to point to the CloudFront distribution domain name obtained in step 6.

        By following these steps, you have configured the web application with CDN on AWS.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Web Applications Should Use CDNs" for AWS using Python, you can follow these steps:

        1. Create an AWS CloudFront distribution:

        ```python theme={null}
        import boto3

        cloudfront = boto3.client('cloudfront')

        response = cloudfront.create_distribution(
            DistributionConfig={
                'CallerReference': 'unique-id', # unique identifier for the distribution
                'Aliases': {
                    'Quantity': 1, # number of CNAMEs (aliases) for the distribution
                    'Items': ['example.com'] # list of CNAMEs for the distribution
                },
                'DefaultRootObject': 'index.html', # default object to serve when no path is specified
                'Origins': {
                    'Quantity': 1, # number of origins for the distribution
                    'Items': [
                        {
                            'Id': 'my-s3-bucket', # unique identifier for the origin
                            'DomainName': 'my-s3-bucket.s3.amazonaws.com', # domain name of the S3 bucket
                            'S3OriginConfig': {
                                'OriginAccessIdentity': '' # optional, use if you want to restrict access to the S3 bucket
                            }
                        }
                    ]
                },
                'DefaultCacheBehavior': {
                    'TargetOriginId': 'my-s3-bucket', # unique identifier for the origin
                    'ForwardedValues': {
                        'QueryString': False, # whether to forward query strings to the origin
                        'Cookies': {
                            'Forward': 'none' # whether to forward cookies to the origin
                        }
                    },
                    'TrustedSigners': {
                        'Enabled': False, # whether to require signed URLs or cookies
                        'Quantity': 0 # number of trusted signers
                    },
                    'ViewerProtocolPolicy': 'redirect-to-https', # whether to redirect HTTP requests to HTTPS
                    'MinTTL': 0 # minimum time-to-live for objects in the cache
                },
                'Comment': 'My CloudFront distribution', # optional comment for the distribution
                'Enabled': True # whether the distribution is enabled
            }
        )

        distribution_id = response['Distribution']['Id']
        ```

        2. Update DNS records:

        Once the CloudFront distribution is created, you need to update your DNS records to point to the CloudFront domain name. You can do this by creating a CNAME record in your DNS provider's control panel that points to the CloudFront domain name.

        3. Test the distribution:

        Once the DNS records have propagated, you can test the CloudFront distribution by accessing your web application using the CloudFront domain name. If everything is working correctly, your web application should be served from the CloudFront edge locations, which will improve performance and reduce latency for your users.

        Note: Remember to update your web application code to use the CloudFront domain name instead of the S3 bucket URL.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Create a CloudFront distribution in front of your web application
        # Replace the UPPER_SNAKE_CASE placeholders with your actual values.

        resource "aws_cloudfront_origin_access_control" "app_oac" {
          name                              = "APP_OAC_NAME" # e.g. "my-app-oac"
          description                       = "Origin access control for app origin"
          origin_access_control_origin_type = "s3"           # use "s3" for S3, "mediastore" or "custom" if different
          signing_behavior                  = "always"
          signing_protocol                  = "sigv4"
        }

        resource "aws_cloudfront_distribution" "app_cdn" {
          enabled             = true
          comment             = "CDN for APP_NAME" # e.g. "CDN for my web application"
          default_root_object = "INDEX_OBJECT"    # e.g. "index.html" for S3 static sites

          aliases = [
            "APP_FQDN", # e.g. "app.example.com"
          ]

          origin {
            origin_id   = "app-origin"
            domain_name = APP_ORIGIN_DOMAIN_NAME  # e.g. aws_s3_bucket.website.bucket_regional_domain_name or ALB DNS name

            # For S3 with OAC
            origin_access_control_id = aws_cloudfront_origin_access_control.app_oac.id

            # For ALB/API, instead of origin_access_control_id, use:
            # custom_origin_config {
            #   http_port              = 80
            #   https_port             = 443
            #   origin_protocol_policy = "https-only"
            #   origin_ssl_protocols   = ["TLSv1.2"]
            # }
          }

          default_cache_behavior {
            target_origin_id       = "app-origin"
            viewer_protocol_policy = "redirect-to-https"
            compress               = true

            allowed_methods = [
              "GET",
              "HEAD",
              "OPTIONS",
              "PUT",
              "POST",
              "PATCH",
              "DELETE",
            ]

            cached_methods = [
              "GET",
              "HEAD",
            ]

            forwarded_values {
              query_string = true

              cookies {
                forward = "all"
              }
            }

            # Adjust TTLs to your app’s needs
            min_ttl     = 0
            default_ttl = 300
            max_ttl     = 86400
          }

          restrictions {
            geo_restriction {
              restriction_type = "none" # or "whitelist"/"blacklist" + locations = [...]
            }
          }

          viewer_certificate {
            acm_certificate_arn            = "ACM_CERT_ARN" # e.g. aws_acm_certificate.app.arn (must be in us-east-1)
            ssl_support_method             = "sni-only"
            minimum_protocol_version       = "TLSv1.2_2021"
            cloudfront_default_certificate = false
          }

          # Optional: logging to an S3 bucket
          # logging_config {
          #   bucket = "LOGGING_BUCKET_NAME.s3.amazonaws.com"
          #   prefix = "cloudfront/"
          # }

          price_class = "PriceClass_All" # or "PriceClass_100"/"PriceClass_200"
        }
        ```

        If you are introducing CloudFront in front of an existing application (e.g., previously accessed directly via an ALB or S3 website endpoint), this creates a new distribution rather than replacing the origin itself; traffic cutover happens when you repoint `APP_FQDN` in DNS (e.g., Route 53) to the distribution’s domain name.

        To verify in Terraform, `terraform plan` should show `+ aws_cloudfront_distribution.app_cdn` (and `+ aws_cloudfront_origin_access_control.app_oac` if used) being created, with `enabled = true` and your origin correctly configured.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
