aws cliでCloudfrontのCNAMEs設定の一括変更

snow
2020-09-01
snow
2020-09-01

導入理由:


システム移行により、
大量なCloudfrontの設定変更が必要となっています。

変更の前提条件:


同じドメインは複数のCloudfrontのCNAMEsに追加することができないため、旧環境のCNAMEsをクリアする必要があります。
DNS(Route53)が旧環境の設定ありの状態で、CloudfrontのCNAMEsを解除できないため、新環境に事前変更する必要があります。

準備:

以下のコマンドで、新環境と旧環境のdistribution設定ファイルを準備します。

```
$ aws cloudfront get-distribution-config --id "xxxxxxxxxxxxx" | jq '.DistributionConfig' > (old/new){domain}.json
```

旧環境のCloudfrontのCNAMEsをクリアした設定ファイルを準備します。

(old){domain}.json 設定ファイルの

```
  “Aliases”: {
    “Items”: [
      “domain”
    ],
    “Quantity”: 1
  }
```

以下のように変更します。

```
  “Aliases”: {
    “Quantity”: 0
  }
```

新環境のCloudfrontのCNAMEsを追加した設定ファイルを準備します。

(new){domain}.json 設定ファイルの

```
  “Aliases”: {
    “Quantity”: 0
  }
```

以下のように変更します。

```
  “Aliases”: {
    “Items”: [
    “domain”
  ],
  “Quantity”: 1
}
```

以下のコマンドで、新環境と旧環境のETagを準備します。

```
$ aws cloudfront get-distribution-config --id "xxxxxxxxxxxxx" | jq '.ETag'
```

実行:


DNS(Route53)のドメインが先に新CloudfrontのDomainNameを設定します。(別Blogで紹介します))

旧環境のCloudfrontのCNAMEsをクリア処理を実行します。

```
$ aws cloudfront update-distribution --id "xxxxxxxxxxxxx" --distribution-config file://(old){domain}.json --if-match 取得した旧環境ETag
```

新環境のCloudfrontにCNAMEsにドメインを追加します。

```
$ aws cloudfront update-distribution --id "xxxxxxxxxxxxx" --distribution-config file://(new)){domain}.json --if-match 取得した新環境ETag
```

注意:

ETagは更新するたびに変更されますので、
update-distributionを実行する前に、毎回Etagを取得しましょう。