AWS SDK を使用して CloudFront ディストリビューションを作成する - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して CloudFront ディストリビューションを作成する

次のコード例は、 CloudFront ディストリビューションを作成する方法を示しています。

CLI
AWS 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 の詳細については、「 コマンドリファレンスCreateDistribution」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

次の例では、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 の詳細については、「 API リファレンスCreateDistribution」の「」を参照してください。 AWS SDK for Java 2.x