建立 SaaS 管理員資源 AWS SDK - AWS SDK 程式碼範例

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

建立 SaaS 管理員資源 AWS SDK

下列程式碼範例示範如何使用各種組態建立多租用戶分佈和分佈租用戶。

Java
SDK for Java 2.x
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

下列範例示範如何使用參數和萬用字元憑證建立多租戶分佈。

import software.amazon.awssdk.core.internal.waiters.ResponseOrException; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.ConnectionMode; 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.HttpVersion; import software.amazon.awssdk.services.cloudfront.model.Method; import software.amazon.awssdk.services.cloudfront.model.SSLSupportMethod; 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 CreateMultiTenantDistribution { public static Distribution CreateMultiTenantDistributionWithCert(CloudFrontClient cloudFrontClient, S3Client s3Client, final String bucketName, final String certificateArn) { // fetch the origin info if necessary 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. CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder .distributionConfig(b1 -> b1 .httpVersion(HttpVersion.HTTP2) .enabled(true) .comment("Template Distribution with cert built with java") .connectionMode(ConnectionMode.TENANT_ONLY) .callerReference(Instant.now().toString()) .viewerCertificate(certBuilder -> certBuilder .acmCertificateArn(certificateArn) .sslSupportMethod(SSLSupportMethod.SNI_ONLY)) .origins(b2 -> b2 .quantity(1) .items(b3 -> b3 .domainName(originDomain) .id(originId) .originPath("/{{tenantName}}") .s3OriginConfig(builder4 -> builder4 .originAccessIdentity( "")))) .tenantConfig(b5 -> b5 .parameterDefinitions(b6 -> b6 .name("tenantName") .definition(b7 -> b7 .stringSchema(b8 -> b8 .comment("tenantName value") .defaultValue("root") .required(false))))) .defaultCacheBehavior(b2 -> b2 .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) .targetOriginId(originId) .cachePolicyId("658327ea-f89d-4fab-a63d-7e88639e58f6") // CachingOptimized Policy .allowedMethods(b4 -> b4 .quantity(2) .items(Method.HEAD, Method.GET))) )); final Distribution distribution = createDistResponse.distribution(); 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")); } return distribution; } public static Distribution CreateMultiTenantDistributionNoCert(CloudFrontClient cloudFrontClient, S3Client s3Client, final String bucketName) { // fetch the origin info if necessary 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. CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder .distributionConfig(b1 -> b1 .httpVersion(HttpVersion.HTTP2) .enabled(true) .comment("Template Distribution with cert built with java") .connectionMode(ConnectionMode.TENANT_ONLY) .callerReference(Instant.now().toString()) .origins(b2 -> b2 .quantity(1) .items(b3 -> b3 .domainName(originDomain) .id(originId) .originPath("/{{tenantName}}") .s3OriginConfig(builder4 -> builder4 .originAccessIdentity( "")))) .tenantConfig(b5 -> b5 .parameterDefinitions(b6 -> b6 .name("tenantName") .definition(b7 -> b7 .stringSchema(b8 -> b8 .comment("tenantName value") .defaultValue("root") .required(false))))) .defaultCacheBehavior(b2 -> b2 .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) .targetOriginId(originId) .cachePolicyId("658327ea-f89d-4fab-a63d-7e88639e58f6") // CachingOptimized Policy .allowedMethods(b4 -> b4 .quantity(2) .items(Method.HEAD, Method.GET))) )); final Distribution distribution = createDistResponse.distribution(); 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")); } return distribution; } }

下列範例示範如何建立與該範本相關聯的分佈租用戶,包括使用上面宣告的參數。請注意,我們不需要在此處新增憑證資訊,因為父範本已涵蓋我們的網域。

import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; import software.amazon.awssdk.services.cloudfront.model.DistributionTenant; import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.RRType; import java.time.Instant; public class CreateDistributionTenant { public static DistributionTenant createDistributionTenantNoCert(CloudFrontClient cloudFrontClient, Route53Client route53Client, String distributionId, String domain, String hostedZoneId) { CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder .distributionId(distributionId) .domains(b1 -> b1 .domain(domain)) .parameters(b2 -> b2 .name("tenantName") .value("myTenant")) .enabled(false) .name("no-cert-tenant") ); final DistributionTenant distributionTenant = createResponse.distributionTenant(); // Then update the Route53 hosted zone to point your domain at the distribution tenant // We fetch the RoutingEndpoint to point to via the default connection group that was created for your tenant final GetConnectionGroupResponse fetchedConnectionGroup = cloudFrontClient.getConnectionGroup(builder -> builder .identifier(distributionTenant.connectionGroupId())); route53Client.changeResourceRecordSets(builder -> builder .hostedZoneId(hostedZoneId) .changeBatch(b1 -> b1 .comment("ChangeBatch comment") .changes(b2 -> b2 .resourceRecordSet(b3 -> b3 .name(domain) .type("CNAME") .ttl(300L) .resourceRecords(b4 -> b4 .value(fetchedConnectionGroup.connectionGroup().routingEndpoint()))) .action("CREATE")) )); return distributionTenant; } }

如果從父範本省略檢視器憑證,則需要改為在與其相關聯的租用戶 (s) 上新增憑證資訊。下列範例示範如何透過涵蓋租用戶必要網域的 ACM 憑證 Arn 來執行此操作。

import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; import software.amazon.awssdk.services.cloudfront.model.DistributionTenant; import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.RRType; import java.time.Instant; public class CreateDistributionTenant { public static DistributionTenant createDistributionTenantWithCert(CloudFrontClient cloudFrontClient, Route53Client route53Client, String distributionId, String domain, String hostedZoneId, String certificateArn) { CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder .distributionId(distributionId) .domains(b1 -> b1 .domain(domain)) .enabled(false) .name("tenant-with-cert") .parameters(b2 -> b2 .name("tenantName") .value("myTenant")) .customizations(b3 -> b3 .certificate(b4 -> b4 .arn(certificateArn))) // NOTE: Cert must be in Us-East-1 and cover the domain provided in this request ); final DistributionTenant distributionTenant = createResponse.distributionTenant(); // Then update the Route53 hosted zone to point your domain at the distribution tenant // We fetch the RoutingEndpoint to point to via the default connection group that was created for your tenant final GetConnectionGroupResponse fetchedConnectionGroup = cloudFrontClient.getConnectionGroup(builder -> builder .identifier(distributionTenant.connectionGroupId())); route53Client.changeResourceRecordSets(builder -> builder .hostedZoneId(hostedZoneId) .changeBatch(b1 -> b1 .comment("ChangeBatch comment") .changes(b2 -> b2 .resourceRecordSet(b3 -> b3 .name(domain) .type("CNAME") .ttl(300L) .resourceRecords(b4 -> b4 .value(fetchedConnectionGroup.connectionGroup().routingEndpoint()))) .action("CREATE")) )); return distributionTenant; } }

下列範例示範如何使用 CloudFront 託管的受管憑證請求來執行此操作。如果您還沒有流向網域的流量,這是理想的選擇。在此情況下,我們會建立 ConnectionGroup 來產生 RoutingEndpoint。然後,我們會使用該 RoutingEndpoint 來建立 DNS 記錄,以驗證網域擁有權並指向 CloudFront。CloudFront 會自動提供權杖,以驗證網域擁有權並建立受管憑證。

import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; import software.amazon.awssdk.services.cloudfront.model.DistributionTenant; import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.RRType; import java.time.Instant; public class CreateDistributionTenant { public static DistributionTenant createDistributionTenantCfHosted(CloudFrontClient cloudFrontClient, Route53Client route53Client, String distributionId, String domain, String hostedZoneId) throws InterruptedException { CreateConnectionGroupResponse createConnectionGroupResponse = cloudFrontClient.createConnectionGroup(builder -> builder .ipv6Enabled(true) .name("cf-hosted-connection-group") .enabled(true)); route53Client.changeResourceRecordSets(builder -> builder .hostedZoneId(hostedZoneId) .changeBatch(b1 -> b1 .comment("cf-hosted domain validation record") .changes(b2 -> b2 .resourceRecordSet(b3 -> b3 .name(domain) .type(RRType.CNAME) .ttl(300L) .resourceRecords(b4 -> b4 .value(createConnectionGroupResponse.connectionGroup().routingEndpoint()))) .action("CREATE")) )); // Give the R53 record time to propagate, if it isn't being returned by servers yet, the following call will fail Thread.sleep(60000); CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder .distributionId(distributionId) .domains(b1 -> b1 .domain(domain)) .connectionGroupId(createConnectionGroupResponse.connectionGroup().id()) .enabled(false) .name("cf-hosted-tenant") .parameters(b2 -> b2 .name("tenantName") .value("myTenant")) .managedCertificateRequest(b3 -> b3 .validationTokenHost(ValidationTokenHost.CLOUDFRONT) ) ); return createResponse.distributionTenant(); } }

下列範例示範如何使用自我託管受管憑證請求來執行此操作。如果您有流向網域的流量,而且在遷移期間無法容忍停機時間,則這是理想的選擇。在此範例結束時,租用戶將以等待網域驗證和 DNS 設定的狀態建立。當您準備好遷移流量時,請依照步驟 【此處】(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html#complete-domain-ownership://) 完成設定。

import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; import software.amazon.awssdk.services.cloudfront.model.DistributionTenant; import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse; import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.RRType; import java.time.Instant; public class CreateDistributionTenant { public static DistributionTenant createDistributionTenantSelfHosted(CloudFrontClient cloudFrontClient, String distributionId, String domain) { CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder .distributionId(distributionId) .domains(b1 -> b1 .domain(domain)) .parameters(b2 -> b2 .name("tenantName") .value("myTenant")) .enabled(false) .name("self-hosted-tenant") .managedCertificateRequest(b3 -> b3 .validationTokenHost(ValidationTokenHost.SELF_HOSTED) .primaryDomainName(domain) ) ); return createResponse.distributionTenant(); } }