君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

AWSのCloudFrontの設定(OriginPath)を、aws-cliから変更する

f:id:karoten512:20181206221710p:plain

いきさつ

デプロイ自動化の一環で、

AWSのCloudFrontの設定をaws-cliから変更したくなった。

(今回変更したのはOriginPath)

前提

  • aws-cliが使用できる環境
  • jpが使用できる環境

出来上がったシェル

# Etagの抽出
RAW_ETAG=$(aws cloudfront get-distribution-config --id "xxxxxxxxx" | jq '.ETag')
ETAG=$(echo ${RAW_ETAG} | sed "s/\"//g")

# 今の設定をファイルとして抽出
aws cloudfront get-distribution-config --id "xxxxxxxxx" | jq '.["DistributionConfig"]' > old_dist.conf

# 抽出した設定ファイルの書き換え
cat old_dist.conf | jq '.["Origins"]["Items"][0]["OriginPath"] = "'/dir_name'"' > new_dist.conf

# 新しい設定の適用
aws cloudfront update-distribution --id "xxxxxxxxx" --distribution-config file://new_dist.conf --if-match ${ETAG}

解説

全体について

CloudFrontの設定を変えるには、

aws cloudfront update-distribution --id "xxxxxxxxx" --distribution-config file://new_dist.conf --if-match ${ETAG}

というコマンドを叩きます。このとき

  • 現在のCloudFront設定のバージョンを表す文字列「Etag」
  • 新しい設定ファイルである「new_dist.conf」

が必要になるので、準備が必要です。

Etagの抽出

RAW_ETAG=$(aws cloudfront get-distribution-config --id "xxxxxxxxx" | jq '.ETag')
ETAG=$(echo ${RAW_ETAG} | sed "s/\"//g")

普通に抽出するとダブルクォーテーションが着いてしまうので、 除去しておきます。

新しい設定ファイルである「new_dist.conf」を生成

# 今の構成ファイルの抽出
aws cloudfront get-distribution-config --id "xxxxxxxxx" | jq '.["DistributionConfig"]' > old_dist.conf

# 抽出した構成ファイルの書き換え
cat old_dist.conf | jq '.["Origins"]["Items"][0]["OriginPath"] = "'/dir_name'"' > new_dist.conf

まず今の構成ファイルを抽出し、

そのファイルの一部(今回でいうとOriginPath)を書き換え、

新しい設定ファイルを生成しておきます。

感想

これだけでもだいぶ便利になった。

CUIはやっぱりよい。