この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは、菊池です。
今回は小ネタです。少し前に、ALB(Application Load Balancer)の機能アップデートで、高度なリクエストルーティングがサポートされました。
[新機能] HTTPヘッダーやクエリ文字列などなどでルーティングができちゃう!!AWS ALBで高度なリクエストルーティングが可能になりました!
従来からサポートされていた、ホストヘッダー、パスパターンに加え、
- HTTPヘッダー
- HTTPリクエストメソッド
- クエリ文字列
- 送信元IPアドレス
に対しての条件が設定可能になりました。
AWS CLI で高度なリクエストルーティングを設定する
この、リクエストルーティングの設定を AWS CLI を使って設定する機会がありましたので、備忘として紹介します。
リクエストルーティングの設定は、elbv2
のcreate-rule
で設定可能です。今回は、以下の条件に対してルールを作成します。
- HTTPヘッダー
- 送信元IPアドレス
前提として、あらかじめ設定対象のALBとリスナー、転送先となるターゲットグループが作成済みである必要があります。実行コマンドは以下のようになります。
aws elbv2 create-rule \
--listener-arn (リスナーのARN) \
--priority (プライオリティ) \
--conditions (条件を記載したJSONファイル) \
--actions (条件にマッチした場合の動作)
条件はファイルにJSONで記載しておきます。以下はHTTPヘッダーとして x-pre-shared-key:PRESHAREDKEY
を評価する設定
[
{
"Field": "http-header",
"HttpHeaderConfig": {
"Values": [
"PRESHAREDKEY"
],
"HttpHeaderName": "x-pre-shared-key"
}
}
]
設定を実行します。
$ aws elbv2 create-rule \
> --listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:listener/app/test/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
> --priority 10 \
> --conditions file://rule.json \
> --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:targetgroup/test-tg01/xxxxxxxxxxxxxxxx
{
"Rules": [
{
"RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:listener-rule/app/test/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/92034cc4876ae583",
"Priority": "10",
"Conditions": [
{
"Field": "http-header",
"HttpHeaderConfig": {
"HttpHeaderName": "x-pre-shared-key",
"Values": [
"PRESHAREDKEY"
]
}
}
],
"Actions": [
{
"Type": "forward",
"TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:targetgroup/test-tg01/xxxxxxxxxxxxxxxx"
}
],
"IsDefault": false
}
]
}
続いて、送信元IPの設定です。JSONは以下のように記載しておきます。
[
{
"Field": "source-ip",
"SourceIpConfig": {
"Values": [
"xxx.xxx.xxx.xxx/32"
]
}
}
]
こちらも設定してみます。
$ aws elbv2 create-rule \
> --listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:listener/app/test/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
> --priority 20 \
> --conditions file://ip-rule.json \
> --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:targetgroup/test-tg01/xxxxxxxxxxxxxxxx
{
"Rules": [
{
"RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:listener-rule/app/test/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/2e9b0ed05f19dc00",
"Priority": "20",
"Conditions": [
{
"Field": "source-ip",
"SourceIpConfig": {
"Values": [
"xxx.xxx.xxx.xxx/32"
]
}
}
],
"Actions": [
{
"Type": "forward",
"TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:targetgroup/test-tg01/xxxxxxxxxxxxxxxx"
}
],
"IsDefault": false
}
]
}
設定後にリスナーを確認すると、ちゃんと設定できていました。
設定したルールを更新するにはmodify-rule、削除はdelete-rule、設定内容の確認はdescribe-rulesで可能です。
最後に
以上です。CLIで設定することで、作業の再現性が確保できるかと思います。AWS CLIでの設定では、ドキュメントのサンプルだけだとわかりにくいこともあるため、備忘として紹介しました。