如何使用 boto 和 python3 使 CloudFront 中的对象失效



我在本页底部找到了与我需要的代码类似的代码。

#!/usr/bin/env python3
from boto.cloudfront import CloudFrontConnection
aws_access_key         = 'BJDJLSMQRWDSC4UPLS6S' # Not real
aws_secret_access_key  = '8xRnWKxRR/93TeQv3pwzMNR222nwe5kjhYweCAij' # Not real
aws_cf_distribution_id = 'foobar35'
objects = [ '/index.html' ]
conn = CloudFrontConnection(aws_access_key, aws_secret_access_key)
print(conn.create_invalidation_request(aws_cf_distribution_id, objects))

当我运行它时,出现以下错误:

$ ./invalidate.py
Traceback (most recent call last):
  File "./invalidate.py", line 14, in <module>
    print(conn.create_invalidation_request(aws_cf_distribution_id, objects))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto/cloudfront/__init__.py", line 263, in create_invalidation_request
    raise CloudFrontServerError(response.status, response.reason, body)
boto.cloudfront.exception.CloudFrontServerError: CloudFrontServerError: 404 Not Found
<?xml version="1.0"?>
<ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2010-11-01/">
  <Error>
    <Type>Sender</Type>
    <Code>NoSuchDistribution</Code>
    <Message>The specified distribution does not exist.</Message>
  </Error>
  <RequestId>343d3d5b-e269-11e5-bc96-eb9a228cf3e7</RequestId>
</ErrorResponse>

我认为问题是我没有确定/index.html 所在的 S3 存储桶。我有大约 20 个存储桶,每个存储桶都以 URL 的域部分命名。我尝试了各种排列,但无济于事。

  • s3://www.example.com.s3.amazonaws.com/index.html
  • s3://www.example.com/index.html
  • /www.example.com/index.html
  • www.example.com/index.html
  • /索引.html

有人可以告诉我如何让它工作吗?

实际错误如下:

<Message>The specified distribution does not exist.</Message>

根据您的代码,您已指定"foobar35"作为您的分配 ID - 这是不正确的。

在尝试使对象失效之前,您需要创建一个分配。创建后,您将收到一个分发 ID,该 ID 应作为参数传递给 create_invalidation_request 方法。

有关更多信息,请参阅:使用 CloudFront 控制台创建或更新 Web 分配。

Vladimir Mukhin 的回答很有帮助:他是正确的,我的发行版 ID 不正确,我需要创建一个发行版。但是,我不知道如何获取我的分配 ID。我通过查看awscli文档找到了它。然而,答案不仅仅是RTFM,因为我需要的信息不容易找到。这是最终帮助我的答案

aws cloudfront list-distributions

有了这些信息,我能够在 Python、Ruby 和 Perl (Paws) API 中找到相似之处,以获得正确的分发 ID,而无需使用命令行。希望这对某人有所帮助。

使用 boto3

def invalidate(distributionId:str, path:str='/*')->str:
  '''
    create a cloudfront invalidation
    parameters:
      distributionId:str: distribution id of the cf distribution
      path:str: path to invalidate, can use wildcard eg. "/*" means all path
    response:
      invalidationId:str: invalidation id
  '''
  cf = boto3.client('cloudfront')
  # Create CloudFront invalidation
  res = cf.create_invalidation(
      DistributionId=distributionId,
      InvalidationBatch={
          'Paths': {
              'Quantity': 1,
              'Items': [
                  path
              ]
          },
          'CallerReference': str(time.time()).replace(".", "")
      }
  )
  invalidation_id = res['Invalidation']['Id']
  return invalidation_id

使用尼克助手

pip install nicHelper

from nicHelper.cloudfront import invalidate
# invalidate(<distributionId>, <path>)
invalidate("EIOJ239OIUOIU","/*")

最新更新