You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询通过Boto3为已有CloudFront分配创建源和行为的API

如何用Boto3为已有的CloudFront分配添加源和行为

存在对应的Boto3 API,你需要使用update_distribution方法——CloudFront的源(Origin)和行为(Behavior)是分配(Distribution)配置的组成部分,无法单独创建,必须通过更新整个分配的配置来添加或修改。

具体操作步骤

  • 首先获取目标分配的当前配置和ETag(更新时需用该参数做并发校验):调用get_distribution方法,从返回结果中提取DistributionConfig和ETag。
  • 修改配置:在DistributionConfig的Origins.Items列表中添加新源,在CacheBehaviors.Items列表中添加对应行为(若要修改默认行为则调整DefaultCacheBehavior字段)。
  • 提交更新:调用update_distribution方法,传入修改后的配置、分配ID和ETag。

示例代码

import boto3

# 初始化CloudFront客户端
cloudfront = boto3.client('cloudfront')

# 替换为你的CloudFront分配ID
distribution_id = 'YOUR_DISTRIBUTION_ID'

# 获取当前分配配置与ETag
distribution_data = cloudfront.get_distribution(Id=distribution_id)
current_config = distribution_data['Distribution']['DistributionConfig']
etag = distribution_data['ETag']

# 添加新源
new_origin = {
    'Id': 'My-Custom-Origin',
    'DomainName': 'your-origin-domain.com',
    'CustomOriginConfig': {
        'HTTPPort': 80,
        'HTTPSPort': 443,
        'OriginProtocolPolicy': 'https-only'
    }
}
current_config['Origins']['Items'].append(new_origin)
current_config['Origins']['Quantity'] += 1

# 添加对应缓存行为
new_cache_behavior = {
    'PathPattern': '/custom-path/*',
    'TargetOriginId': 'My-Custom-Origin',
    'ViewerProtocolPolicy': 'redirect-to-https',
    'MinTTL': 300
}
current_config['CacheBehaviors']['Items'].append(new_cache_behavior)
current_config['CacheBehaviors']['Quantity'] += 1

# 执行分配更新
update_result = cloudfront.update_distribution(
    DistributionConfig=current_config,
    Id=distribution_id,
    IfMatch=etag
)

print(f"分配更新完成,ID: {update_result['Distribution']['Id']}")

注意事项

  • 需保证Origins.Quantity和CacheBehaviors.Quantity的值分别与对应Items列表的长度一致,否则会触发参数校验错误。
  • 缓存行为的路径模式有匹配优先级,添加时需注意顺序(CloudFront会按列表顺序匹配路径)。
  • 分配更新后,CloudFront需要几分钟时间完成部署,期间配置不会立即生效。

内容的提问来源于stack exchange,提问作者Bhavesh R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:50:38