将 CreateDistribution 与 Amazon SDK 或命令行工具配合使用 - Amazon CloudFront
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreateDistribution 与 Amazon SDK 或命令行工具配合使用

以下代码示例演示如何使用 CreateDistribution

CLI
Amazon CLI

创建 CloudFront 分配

以下示例使用命令行参数为名为 awsexamplebucket 的 S3 存储桶创建分配,并将 index.html 指定为默认根对象:

aws cloudfront create-distribution \ --origin-domain-name awsexamplebucket.s3.amazonaws.com \ --default-root-object index.html

您可以在 JSON 文件中提供分配配置,而不必使用命令行参数,如以下示例所示:

aws cloudfront create-distribution \ --distribution-config file://dist-config.json

文件 dist-config.json 是当前文件夹中包含以下内容的 JSON 文档:

{ "CallerReference": "cli-example", "Aliases": { "Quantity": 0 }, "DefaultRootObject": "index.html", "Origins": { "Quantity": 1, "Items": [ { "Id": "awsexamplebucket.s3.amazonaws.com-cli-example", "DomainName": "awsexamplebucket.s3.amazonaws.com", "OriginPath": "", "CustomHeaders": { "Quantity": 0 }, "S3OriginConfig": { "OriginAccessIdentity": "" } } ] }, "OriginGroups": { "Quantity": 0 }, "DefaultCacheBehavior": { "TargetOriginId": "awsexamplebucket.s3.amazonaws.com-cli-example", "ForwardedValues": { "QueryString": false, "Cookies": { "Forward": "none" }, "Headers": { "Quantity": 0 }, "QueryStringCacheKeys": { "Quantity": 0 } }, "TrustedSigners": { "Enabled": false, "Quantity": 0 }, "ViewerProtocolPolicy": "allow-all", "MinTTL": 0, "AllowedMethods": { "Quantity": 2, "Items": [ "HEAD", "GET" ], "CachedMethods": { "Quantity": 2, "Items": [ "HEAD", "GET" ] } }, "SmoothStreaming": false, "DefaultTTL": 86400, "MaxTTL": 31536000, "Compress": false, "LambdaFunctionAssociations": { "Quantity": 0 }, "FieldLevelEncryptionId": "" }, "CacheBehaviors": { "Quantity": 0 }, "CustomErrorResponses": { "Quantity": 0 }, "Comment": "", "Logging": { "Enabled": false, "IncludeCookies": false, "Bucket": "", "Prefix": "" }, "PriceClass": "PriceClass_All", "Enabled": true, "ViewerCertificate": { "CloudFrontDefaultCertificate": true, "MinimumProtocolVersion": "TLSv1", "CertificateSource": "cloudfront" }, "Restrictions": { "GeoRestriction": { "RestrictionType": "none", "Quantity": 0 } }, "WebACLId": "", "HttpVersion": "http2", "IsIPV6Enabled": true }

无论您使用命令行参数还是 JSON 文件提供分配信息,输出都相同:

{ "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/EMLARXS9EXAMPLE", "ETag": "E9LHASXEXAMPLE", "Distribution": { "Id": "EMLARXS9EXAMPLE", "ARN": "arn:aws:cloudfront::123456789012:distribution/EMLARXS9EXAMPLE", "Status": "InProgress", "LastModifiedTime": "2019-11-22T00:55:15.705Z", "InProgressInvalidationBatches": 0, "DomainName": "d111111abcdef8.cloudfront.net", "ActiveTrustedSigners": { "Enabled": false, "Quantity": 0 }, "DistributionConfig": { "CallerReference": "cli-example", "Aliases": { "Quantity": 0 }, "DefaultRootObject": "index.html", "Origins": { "Quantity": 1, "Items": [ { "Id": "awsexamplebucket.s3.amazonaws.com-cli-example", "DomainName": "awsexamplebucket.s3.amazonaws.com", "OriginPath": "", "CustomHeaders": { "Quantity": 0 }, "S3OriginConfig": { "OriginAccessIdentity": "" } } ] }, "OriginGroups": { "Quantity": 0 }, "DefaultCacheBehavior": { "TargetOriginId": "awsexamplebucket.s3.amazonaws.com-cli-example", "ForwardedValues": { "QueryString": false, "Cookies": { "Forward": "none" }, "Headers": { "Quantity": 0 }, "QueryStringCacheKeys": { "Quantity": 0 } }, "TrustedSigners": { "Enabled": false, "Quantity": 0 }, "ViewerProtocolPolicy": "allow-all", "MinTTL": 0, "AllowedMethods": { "Quantity": 2, "Items": [ "HEAD", "GET" ], "CachedMethods": { "Quantity": 2, "Items": [ "HEAD", "GET" ] } }, "SmoothStreaming": false, "DefaultTTL": 86400, "MaxTTL": 31536000, "Compress": false, "LambdaFunctionAssociations": { "Quantity": 0 }, "FieldLevelEncryptionId": "" }, "CacheBehaviors": { "Quantity": 0 }, "CustomErrorResponses": { "Quantity": 0 }, "Comment": "", "Logging": { "Enabled": false, "IncludeCookies": false, "Bucket": "", "Prefix": "" }, "PriceClass": "PriceClass_All", "Enabled": true, "ViewerCertificate": { "CloudFrontDefaultCertificate": true, "MinimumProtocolVersion": "TLSv1", "CertificateSource": "cloudfront" }, "Restrictions": { "GeoRestriction": { "RestrictionType": "none", "Quantity": 0 } }, "WebACLId": "", "HttpVersion": "http2", "IsIPV6Enabled": true } } }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 CreateDistribution

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

以下示例使用 Amazon Simple Storage Service (Amazon S3) 桶作为内容来源。

创建分配后,该代码会创建一个 CloudFrontWaiter,等待分配部署完成后再返回该分配

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.internal.waiters.ResponseOrException; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse; import software.amazon.awssdk.services.cloudfront.model.Distribution; import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse; import software.amazon.awssdk.services.cloudfront.model.ItemSelection; import software.amazon.awssdk.services.cloudfront.model.Method; import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy; import software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter; import software.amazon.awssdk.services.s3.S3Client; import java.time.Instant; public class CreateDistribution { private static final Logger logger = LoggerFactory.getLogger(CreateDistribution.class); public static Distribution createDistribution(CloudFrontClient cloudFrontClient, S3Client s3Client, final String bucketName, final String keyGroupId, final String originAccessControlId) { final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers() .get("x-amz-bucket-region").get(0); final String originDomain = bucketName + ".s3." + region + ".amazonaws.com"; String originId = originDomain; // Use the originDomain value for the originId. // The service API requires some deprecated methods, such as // DefaultCacheBehavior.Builder#minTTL and #forwardedValue. CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder .distributionConfig(b1 -> b1 .origins(b2 -> b2 .quantity(1) .items(b3 -> b3 .domainName(originDomain) .id(originId) .s3OriginConfig(builder4 -> builder4 .originAccessIdentity( "")) .originAccessControlId( originAccessControlId))) .defaultCacheBehavior(b2 -> b2 .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) .targetOriginId(originId) .minTTL(200L) .forwardedValues(b5 -> b5 .cookies(cp -> cp .forward(ItemSelection.NONE)) .queryString(true)) .trustedKeyGroups(b3 -> b3 .quantity(1) .items(keyGroupId) .enabled(true)) .allowedMethods(b4 -> b4 .quantity(2) .items(Method.HEAD, Method.GET) .cachedMethods(b5 -> b5 .quantity(2) .items(Method.HEAD, Method.GET)))) .cacheBehaviors(b -> b .quantity(1) .items(b2 -> b2 .pathPattern("/index.html") .viewerProtocolPolicy( ViewerProtocolPolicy.ALLOW_ALL) .targetOriginId(originId) .trustedKeyGroups(b3 -> b3 .quantity(1) .items(keyGroupId) .enabled(true)) .minTTL(200L) .forwardedValues(b4 -> b4 .cookies(cp -> cp .forward(ItemSelection.NONE)) .queryString(true)) .allowedMethods(b5 -> b5.quantity(2) .items(Method.HEAD, Method.GET) .cachedMethods(b6 -> b6 .quantity(2) .items(Method.HEAD, Method.GET))))) .enabled(true) .comment("Distribution built with java") .callerReference(Instant.now().toString()))); final Distribution distribution = createDistResponse.distribution(); logger.info("Distribution created. DomainName: [{}] Id: [{}]", distribution.domainName(), distribution.id()); logger.info("Waiting for distribution to be deployed ..."); try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) { ResponseOrException<GetDistributionResponse> responseOrException = cfWaiter .waitUntilDistributionDeployed(builder -> builder.id(distribution.id())) .matched(); responseOrException.response() .orElseThrow(() -> new RuntimeException("Distribution not created")); logger.info("Distribution deployed. DomainName: [{}] Id: [{}]", distribution.domainName(), distribution.id()); } return distribution; } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 CreateDistribution

PowerShell
适用于 PowerShell 的工具

示例 1:创建配置了日志记录和缓存的基本 CloudFront 分配。

$origin = New-Object Amazon.CloudFront.Model.Origin $origin.DomainName = "ps-cmdlet-sample.s3.amazonaws.com" $origin.Id = "UniqueOrigin1" $origin.S3OriginConfig = New-Object Amazon.CloudFront.Model.S3OriginConfig $origin.S3OriginConfig.OriginAccessIdentity = "" New-CFDistribution ` -DistributionConfig_Enabled $true ` -DistributionConfig_Comment "Test distribution" ` -Origins_Item $origin ` -Origins_Quantity 1 ` -Logging_Enabled $true ` -Logging_IncludeCookie $true ` -Logging_Bucket ps-cmdlet-sample-logging.s3.amazonaws.com ` -Logging_Prefix "help/" ` -DistributionConfig_CallerReference Client1 ` -DistributionConfig_DefaultRootObject index.html ` -DefaultCacheBehavior_TargetOriginId $origin.Id ` -ForwardedValues_QueryString $true ` -Cookies_Forward all ` -WhitelistedNames_Quantity 0 ` -TrustedSigners_Enabled $false ` -TrustedSigners_Quantity 0 ` -DefaultCacheBehavior_ViewerProtocolPolicy allow-all ` -DefaultCacheBehavior_MinTTL 1000 ` -DistributionConfig_PriceClass "PriceClass_All" ` -CacheBehaviors_Quantity 0 ` -Aliases_Quantity 0
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 CreateDistribution

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 CloudFront 与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。