Search code examples
amazon-web-servicesaws-sdkamazon-cloudfrontaws-sdk-js

Cloudfront exception "The If-Match version is missing or not valid for the resource." when updating distribution


When updating a Cloudfront distribution using the AWS Node SDK I get the following exception:

  message:
   'The If-Match version is missing or not valid for the resource.',
  code: 'InvalidIfMatchVersion',
  time: 2020-08-23T19:37:22.291Z,
  requestId: '43a7707f-7177-4396-8013-4a704b7b11ea',
  statusCode: 400,
  retryable: false,
  retryDelay: 57.05741843025996 }

What am I doing wrong here?


Solution

  • This error occurs because you need to first get the current distribution config with cloudfront.getDistributionConfig and then copy the ETag and DistributionConfig fields into your cloudfront.updateDistribution call. You modify the DistributionConfig as needed to achieve the actual config update you're trying to do.

    The docs do a poor job of explaining this (the instructions are for the REST API instead of the actual SDK you're using).

    The following is an example of updating a Cloudfront distribution to be disabled by pulling the latest distribution config, modifying it, and then performing an update with it:

    async function disable_cloudfront_distribution(dist_id) {
        // We need to pull the previous distribution config to update it.
        const previous_distribution_config = await cloudfront.getDistributionConfig({
            Id: dist_id
        }).promise();
        const e_tag = previous_distribution_config.ETag;
    
        // Update config to be disabled
        previous_distribution_config.DistributionConfig.Enabled = false;
    
        // Create update distribution request with distribution ID
        // and the copied config along with the returned etag for ifmatch.
        const params = {
            Id: dist_id,
            DistributionConfig: previous_distribution_config.DistributionConfig,
            IfMatch: e_tag
        };
    
        return cloudfront.updateDistribution(params).promise();
    }