更新分发时出现 Cloudfront 异常 "The If-Match version is missing or not valid for the resource."

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

使用 AWS Node SDK 更新 Cloudfront 分发时,出现以下异常:

  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 }

我做错了什么?

发生此错误是因为您需要先使用 cloudfront.getDistributionConfig 获取当前分发配置,然后将 ETagDistributionConfig 字段复制到您的 cloudfront.updateDistribution 调用中。您根据需要修改 DistributionConfig 以实现您尝试执行的实际配置更新。

文档对此的解释做得很差(说明是针对 REST API 而不是您正在使用的实际 SDK)。

以下是更新要禁用的 Cloudfront 分发的示例,方法是拉取最新的分发配置,修改它,然后使用它执行更新:

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();
}