本文主要是介绍AWS清除CloudFront缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
运行之前,提供AWS密钥
import boto3def find_cloudfront_distribution_id(domain_name, aws_access_key_id, aws_secret_access_key):# 创建 CloudFront 资源cloudfront = boto3.client('cloudfront', aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)# 获取所有 CloudFront 分配distributions = cloudfront.list_distributions()['DistributionList']['Items']for distribution in distributions:# 检查分配是否有别名if 'Aliases' in distribution and 'Items' in distribution['Aliases']:# 检查分配的域名是否包含所提供的域名for alias in distribution['Aliases']['Items']:if alias == domain_name:return distribution['Id']return Nonedef invalidate_cloudfront_cache(distribution_id, paths, aws_access_key_id, aws_secret_access_key):# 创建 CloudFront 客户端cloudfront = boto3.client('cloudfront', aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)# 创建失效批次invalidation = {'DistributionId': distribution_id,'InvalidationBatch': {'Paths': {'Quantity': len(paths),'Items': paths},'CallerReference': 'unique-identifier' # 为失效批次提供唯一标识符}}# 提交失效请求response = cloudfront.create_invalidation(**invalidation)# 检查失效请求是否成功if response['ResponseMetadata']['HTTPStatusCode'] == 201:print("缓存失效请求成功。")else:print("缓存失效请求失败。")# 输入要清理的域名
domain_name = input('请输入需要清理缓存的域名:\n')# AWS 访问密钥和秘密访问密钥
aws_access_key_id = ''
aws_secret_access_key = ''# 查找 CloudFront 分配的 ID
distribution_id = find_cloudfront_distribution_id(domain_name, aws_access_key_id, aws_secret_access_key)if distribution_id:# 要失效的路径paths_to_invalidate = ['/*']# 失效缓存invalidate_cloudfront_cache(distribution_id, paths_to_invalidate, aws_access_key_id, aws_secret_access_key)else:print(f"未找到与域名 '{domain_name}' 相关联的 CloudFront 分配")
这篇关于AWS清除CloudFront缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!