forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateDistribution.go
More file actions
190 lines (165 loc) · 6.29 KB
/
CreateDistribution.go
File metadata and controls
190 lines (165 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// snippet-start:[cloudfront.go-v2.CreateDistribution]
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudfront"
cloudfrontTypes "github.com/aws/aws-sdk-go-v2/service/cloudfront/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// CFDistributionAPI defines the interface for the CreateDistribution function.
// We use this interface to test the function using a mocked service.
type CFDistributionAPI interface {
CreateDistribution(ctx context.Context, bucketName, certificateSSLArn, domain string) (*cloudfront.CreateDistributionOutput, error)
createoriginAccessIdentity(ctx context.Context, domainName string) (string, error)
}
type CFDistributionAPIImpl struct {
s3Client *s3.Client
cloudfrontClient *cloudfront.Client
}
func createCFDistribution(s3client *s3.Client, cloudfront *cloudfront.Client) CFDistributionAPI {
return &CFDistributionAPIImpl{
s3Client: s3client,
cloudfrontClient: cloudfront,
}
}
func (c *CFDistributionAPIImpl) CreateDistribution(ctx context.Context, bucketName, certificateSSLArn, domain string) (*cloudfront.CreateDistributionOutput, error) {
locationOutput, err := c.s3Client.GetBucketLocation(ctx, &s3.GetBucketLocationInput{Bucket: aws.String(bucketName)})
if err != nil {
return nil, err
}
originDomain := bucketName + ".s3." + string(locationOutput.LocationConstraint) + ".amazonaws.com"
originAccessIdentityID, err := c.createoriginAccessIdentity(ctx, domain)
if err != nil {
return nil, err
}
cloudfrontResponse, err := c.cloudfrontClient.CreateDistribution(ctx, &cloudfront.CreateDistributionInput{
DistributionConfig: &cloudfrontTypes.DistributionConfig{
Enabled: aws.Bool(true),
CallerReference: &originDomain,
Comment: &originDomain,
IsIPV6Enabled: aws.Bool(false),
PriceClass: cloudfrontTypes.PriceClassPriceClass100,
HttpVersion: cloudfrontTypes.HttpVersionHttp11,
DefaultRootObject: aws.String("index.html"),
Aliases: &cloudfrontTypes.Aliases{
Quantity: aws.Int32(1),
Items: []string{domain},
},
ViewerCertificate: &cloudfrontTypes.ViewerCertificate{
ACMCertificateArn: aws.String(certificateSSLArn),
SSLSupportMethod: cloudfrontTypes.SSLSupportMethodSniOnly,
},
CustomErrorResponses: &cloudfrontTypes.CustomErrorResponses{
Quantity: aws.Int32(1),
Items: []cloudfrontTypes.CustomErrorResponse{
{
ErrorCode: aws.Int32(403),
ResponseCode: aws.String("200"),
ErrorCachingMinTTL: aws.Int64(10),
ResponsePagePath: aws.String("/index.html"),
},
},
},
Origins: &cloudfrontTypes.Origins{
Quantity: aws.Int32(1),
Items: []cloudfrontTypes.Origin{
{
DomainName: aws.String(originDomain),
Id: aws.String(originDomain),
S3OriginConfig: &cloudfrontTypes.S3OriginConfig{
OriginAccessIdentity: aws.String("origin-access-identity/cloudfront/" + originAccessIdentityID),
},
},
},
},
CacheBehaviors: nil,
DefaultCacheBehavior: &cloudfrontTypes.DefaultCacheBehavior{
TargetOriginId: aws.String(originDomain),
Compress: aws.Bool(true),
ViewerProtocolPolicy: cloudfrontTypes.ViewerProtocolPolicyRedirectToHttps,
AllowedMethods: &cloudfrontTypes.AllowedMethods{
Quantity: aws.Int32(2),
Items: []cloudfrontTypes.Method{
cloudfrontTypes.MethodGet,
cloudfrontTypes.MethodHead,
},
},
},
},
})
if err != nil {
return nil, err
}
return cloudfrontResponse, nil
}
func (c *CFDistributionAPIImpl) createoriginAccessIdentity(ctx context.Context, domainName string) (string, error) {
oai, err := c.cloudfrontClient.CreateCloudFrontOriginAccessIdentity(ctx, &cloudfront.CreateCloudFrontOriginAccessIdentityInput{
CloudFrontOriginAccessIdentityConfig: &cloudfrontTypes.CloudFrontOriginAccessIdentityConfig{
CallerReference: aws.String(domainName),
Comment: aws.String(domainName),
},
})
if err != nil {
return "", err
}
return *oai.CloudFrontOriginAccessIdentity.Id, nil
}
var (
// bucketName is the name of the S3 bucket to create a CloudFront distribution for.
bucketName = ""
// certificateSSLArn is the ARN value of the certificate issued by the AWS Certificate Manager (ACM).
// When testing, please check and copy and paste the ARN of the pre-issued certificate.
// If you don't know how to create a TLS/SSL certificate using ACM, follow the link below.
// https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html
certificateSSLArn = ""
// domain refers to the domain that will be used in conjunction with CloudFront and Amazon Route 53.
// For testing, please enter a domain that is registered in Route 53 and will be used in conjunction with CloudFront.
domain = ""
)
// main uses the AWS SDK for Go V2 to create an Amazon CloudFront distribution.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
flag.StringVar(&bucketName, "bucket", "", "amzn-s3-demo-bucket")
flag.StringVar(&certificateSSLArn, "cert", "", "<AWS CERTIFICATE MANGER ARN>")
flag.StringVar(&domain, "domain", "", "<YOUR DOMAIN>")
flag.Parse()
if bucketName == "" {
log.Println(errors.New("please setup bucket name"))
return
}
if certificateSSLArn == "" {
log.Println(errors.New("please setup certificate ARN"))
return
}
if domain == "" {
log.Println(errors.New("please setup your domain"))
return
}
ctx := context.Background()
sdkConfig, err := config.LoadDefaultConfig(ctx)
if err != nil {
fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
fmt.Println(err)
return
}
s3Client := s3.NewFromConfig(sdkConfig)
cloudfrontClient := cloudfront.NewFromConfig(sdkConfig)
cfDistribution := createCFDistribution(s3Client, cloudfrontClient)
result, err := cfDistribution.CreateDistribution(ctx, bucketName, certificateSSLArn, domain)
if err != nil {
fmt.Println("Couldn't create distribution. Please check error message and try again.")
fmt.Println(err)
return
}
fmt.Println(result.Distribution.ARN)
}
// snippet-end:[cloudfront.go-v2.CreateDistribution]