> ## 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 compress objects automatically remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of CloudFront web distributions not automatically compressing web content in AWS using the AWS console, please follow the below steps:

        1. Open the AWS Management Console and navigate to the CloudFront service.

        2. Select the distribution that needs to be remediated.

        3. Click on the "Behaviors" tab.

        4. Click on the "Create Behavior" button.

        5. In the "Create Behavior" dialog box, set the following values:

        * Path Pattern: \*
        * Viewer Protocol Policy: Redirect HTTP to HTTPS
        * Allowed HTTP Methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
        * Compress Objects Automatically: Yes
        * Cache Based on Selected Request Headers: None

        6. Click on the "Create" button to create the new behavior.

        7. Wait for the distribution to update and propagate the changes.

        After following these steps, CloudFront web distributions will automatically compress web content.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "CloudFront Web Distributions Should Automatically Compress Web Content" for AWS using AWS CLI, follow the below steps:

        1. Open the AWS CLI on your local machine.

        2. Run the following command to get the ID of the distribution for which you want to enable automatic compression:

           ```
           aws cloudfront list-distributions --query "DistributionList.Items[].{Id:Id,DomainName:DomainName}"
           ```

           This will return a list of all your CloudFront distributions along with their IDs and domain names.

        3. Once you have the distribution ID, run the following command to update the distribution configuration to enable automatic compression:

           ```
           aws cloudfront update-distribution --id <distribution-id> --distribution-config '{"Enabled":true,"Compress":true,"DefaultCacheBehavior":{"Compress":true}}'
           ```

           Replace `<distribution-id>` with the ID of the distribution you want to update.

        4. After running the above command, the distribution configuration will be updated to enable automatic compression for web content.

        5. Verify the changes by running the following command:

           ```
           aws cloudfront get-distribution --id <distribution-id> --query "Distribution.DistributionConfig.DefaultCacheBehavior"
           ```

           This will return the configuration of the default cache behavior for the distribution, which should now have the "Compress" property set to true.

        By following the above steps, you can remediate the misconfiguration "CloudFront Web Distributions Should Automatically Compress Web Content" for AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of CloudFront web distributions not automatically compressing web content in AWS using Python, you can follow these steps:

        1. Import the required AWS SDK modules using the following code:

        ```python theme={null}
        import boto3
        from botocore.exceptions import ClientError
        ```

        2. Create a boto3 client for CloudFront using the following code:

        ```python theme={null}
        client = boto3.client('cloudfront')
        ```

        3. Get a list of all CloudFront distributions using the following code:

        ```python theme={null}
        try:
            response = client.list_distributions()
            distributions = response['DistributionList']['Items']
        except ClientError as e:
            print(e)
        ```

        4. Iterate through each distribution and check if it has a default cache behavior with a gzip compression enabled using the following code:

        ```python theme={null}
        for distribution in distributions:
            try:
                response = client.get_distribution_config(Id=distribution['Id'])
                config = response['DistributionConfig']
                if config['DefaultCacheBehavior']['Compress']:
                    print(f"Gzip compression is already enabled for {distribution['Id']}")
                else:
                    config['DefaultCacheBehavior']['Compress'] = True
                    response = client.update_distribution(
                        DistributionConfig=config,
                        Id=distribution['Id'],
                        IfMatch=response['ETag']
                    )
                    print(f"Gzip compression enabled for {distribution['Id']}")
            except ClientError as e:
                print(e)
        ```

        5. Save the Python script and run it to remediate the misconfiguration.

        This script will enable gzip compression for all CloudFront distributions that do not have it enabled by updating the default cache behavior of each distribution.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "aws_cloudfront_distribution" "WEB_DISTRIBUTION" {
          # Existing arguments for your distribution
          enabled             = true
          default_root_object = "index.html"

          origins {
            domain_name = "ORIGIN_DOMAIN_NAME" # e.g. myapp.s3.amazonaws.com or api.example.com
            origin_id   = "ORIGIN_ID"

            # add origin configuration as needed
          }

          default_cache_behavior {
            target_origin_id       = "ORIGIN_ID"
            viewer_protocol_policy = "redirect-to-https"

            allowed_methods  = ["GET", "HEAD"]
            cached_methods   = ["GET", "HEAD"]
            compress         = true  # Enable automatic compression (matches CLI fix)

            forwarded_values {
              query_string = false

              cookies {
                forward = "none"
              }
            }
          }

          # ...other required distribution settings (viewer_certificate, restrictions, etc.)
        }
        ```

        Changing `compress` from `false` to `true` (or adding it) updates the distribution in place and should not force replacement.

        To verify, `terraform plan` should show an in-place update on `aws_cloudfront_distribution.WEB_DISTRIBUTION` with `default_cache_behavior.compress` changing from `false` (or `null`) to `true`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
