package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudfront"
)
func main() {
id := "XXXXXXXXXXXXX"
sub_domain := "test02"
hosted_zone_name := "vamdemic.com"
svc := cloudfront.New(session.New())
// CloudFront設定情報の読み込み
DistrbutionConfig, err := GetCloudFrontDistributionConfig(svc, id)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(DistrbutionConfig)
// サブドメインエイリアスを追加
Added_DistributionConfig, err := AddCloudFrontDistributionConfig(DistrbutionConfig.DistributionConfig, sub_domain, hosted_zone_name)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(Added_DistributionConfig)
// CloudFront設定のアップデート
UpdateCloudFrontDistribution(svc, id, Added_DistributionConfig, *DistrbutionConfig.ETag)
}
func GetCloudFrontDistributionConfig(svc *cloudfront.CloudFront, id string) (*cloudfront.GetDistributionConfigOutput, error) {
input := &cloudfront.GetDistributionConfigInput{
Id: aws.String(id),
}
result, err := svc.GetDistributionConfig(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cloudfront.ErrCodeNoSuchDistribution:
fmt.Println(cloudfront.ErrCodeNoSuchDistribution, aerr.Error())
case cloudfront.ErrCodeAccessDenied:
fmt.Println(cloudfront.ErrCodeAccessDenied, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return nil, err
}
return result, nil
}
func AddCloudFrontDistributionConfig(DistributionConfig *cloudfront.DistributionConfig, sub_domain string, hosted_zone_name string) (*cloudfront.DistributionConfig, error) {
domain := fmt.Sprintf("%s.%s", sub_domain, hosted_zone_name)
// Alias部分の配列にドメイン名を追加
DistributionConfig.Aliases.Items = append(DistributionConfig.Aliases.Items, &domain)
// Aliasをカウントする要素をインクリメント
// ※ここがDistributionConfig.Aliases.Itemsの数と一致しないと、UpdateDistributionをするときに400になって怒られる
*DistributionConfig.Aliases.Quantity++
return DistributionConfig, nil
}
func UpdateCloudFrontDistribution(svc *cloudfront.CloudFront, id string, DistributionConfig *cloudfront.DistributionConfig, etag string) {
input := &cloudfront.UpdateDistributionInput{
DistributionConfig: DistributionConfig, //ドメイン追加した構成情報を指定する
Id: aws.String(id),
IfMatch: aws.String(etag), // ETagと呼ばれるトランザクションIDのようなものを指定する必要がある。コレは、GetDistributionConfigをしたときに取得できるのでそこから引っ張る
}
result, err := svc.UpdateDistribution(input)
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}