ALBのfixed-response設定をawscliでやってみた

AWSCLIでALBのfixed-responseを設定する際に、具体的なパラメータが分かりづらかったのでまとめてみました。ActionにてFixedResponseConfigを設定する際の参考にしてください。
2018.08.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、臼田です。

先日ALBで新しく固定レスポンスが返せるようになっています。この機能についての説明は下記をご確認ください。

[新機能]EC2やS3不要!ALBだけでメンテナンス画面を表示するなど固定レスポンスが返せるようになりました!

早速こちらをawscliから実行しようとしたらハマったので、設定方法について共有します。

ハマったポイント

awscliでこの設定を行うとき、elbv2create-rule等を使います。ALBやListenerについては作成済みの前提で勧めます。

問題は--actionsオプションに新しく追加されたFixedResponseConfigの書き方で、awscliのリファレンスには次のように書かれています。

FixedResponseConfig={MessageBody=string,StatusCode=string,ContentType=string}

しかしながら、このまま実行すると下記のようなエラーになります。

$ aws elbv2 create-rule \
 --listener-arn arn省略 \
 --conditions Field=path-pattern,Values='/img/*' \
 --priority 2 \
 --actions Type=fixed-response,FixedResponseConfig={MessageBody=test,StatusCode=503,ContentType=text/plain}

Parameter validation failed:
Invalid type for parameter Actions[0].FixedResponseConfig, value: MessageBody=test, type: <type 'unicode'>, valid types: <type 'dict'>
Invalid type for parameter Actions[1].FixedResponseConfig, value: StatusCode=503, type: <type 'unicode'>, valid types: <type 'dict'>
Invalid type for parameter Actions[2].FixedResponseConfig, value: ContentType=text/plain, type: <type 'unicode'>, valid types: <type 'dict'>

適切な書き方

FixedResponseConfig内の値全体をダブルクオーテーションでくくるとうまくいきます。

$ aws elbv2 create-rule \
 --listener-arn arn省略 \
 --conditions Field=path-pattern,Values='/img/*' \
 --priority 2 \
 --actions Type=fixed-response,FixedResponseConfig={"MessageBody=test,StatusCode=503,ContentType=text/plain"}
{
    "Rules": [
        {
            "Priority": "2",
            "Conditions": [
                {
                    "Field": "path-pattern",
                    "Values": [
                        "/img/*"
                    ]
                }
            ],
            "RuleArn": "arn省略",
            "IsDefault": false,
            "Actions": [
                {
                    "Type": "fixed-response",
                    "FixedResponseConfig": {
                        "ContentType": "text/plain",
                        "MessageBody": "test",
                        "StatusCode": "503"
                    }
                }
            ]
        }
    ]
}

まとめ

GUIで触る分には細かいパラメータのフォーマットを気にしなくていいのでハマることはないですが、cliの場合には脅威になりますね。

参考になれば幸いです。