CUEBiC TEC BLOG

キュービックTECチームの技術ネタを投稿しております。

AWSCLIを使ってALBのリスナールールを変更するズラ!!

初めまして、キュービックでSREをやっているkmsn17です。 もうすぐGWに入りますが、みなさんはどのような休日を過ごされますでしょうか?

さてさて、GWに入る前にキュービックのテック記事について紹介します。 皆さん、インスタンスを構築する際に何を使っていますか?

僕はAWSCLIを使ってEC2を構築します。 コマンドを使って構築することで、コマンドやプログラムに対するアレルギーがなくなります。 Scriptを書いたり、プログラムを書くための基盤が身に付きます。 また、手順書を書く際にGUIだとインターフェイスの画面が変わるのでドキュメンを更新する必要がありますが、 コマンドだとその必要がなくなります。

インフラエンジニアには便利でcoolなツールです。 今回ですが、AWSCLIを使ってALBのリスナールールを構築したいと思います!! ヨッ!!Let's start!!

Target Groupの作成

実行コマンドの例

aws elbv2 create-target-group 
--name <Target Group Name> 
--protocol <Protocol Name>
--port <Port Number> 
--vpc-id <VPC ID>

実行コマンドの結果

aws elbv2 create-target-group --name kmsn17-alb-tg --protocol HTTP --port 80 --vpc-id vpc-xxxxxxxxx
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxx",
            "TargetGroupName": "kmsn17-alb-tg",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-xxxxxxxxx",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200"
            },
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}

ALBの作成

実行コマンドの例

aws elbv2 create-load-balancer 
--name  <ALB Name>
--subnets <Subnet ID> <Subnet ID>
--security-groups <SecurityGroup ID>

実行コマンドの結果

aws elbv2 create-load-balancer --name kmsn17-alb --subnets subnet-xxxxxxxxx subnet-xxxxxxxxx --security-groups sg-
{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:loadbalancer/app/kmsn17-alb/xxxxxxxxxxxx",
            "DNSName": "kmsn17-alb-xxxxxxxxxxxx.ap-northeast-1.elb.amazonaws.com",
            "CanonicalHostedZoneId": "xxxxxxxxxxxxx",
            "CreatedTime": "2022-04-13T09:14:28.760000+00:00",
            "LoadBalancerName": "kmsn17-alb",
            "Scheme": "internet-facing",
            "VpcId": "vpc-xxxxxxxxx",
            "State": {
                "Code": "provisioning"
            },
            "Type": "application",
            "AvailabilityZones": [
                {
                    "ZoneName": "ap-northeast-1c",
                    "SubnetId": "subnet-xxxxxxxxxx",
                    "LoadBalancerAddresses": []
                },
                {
                    "ZoneName": "ap-northeast-1d",
                    "SubnetId": "subnet-xxxxxxxxx",
                    "LoadBalancerAddresses": []
                }
            ],
            "SecurityGroups": [
                "sg-xxxxxxxxxxxxxxxxxxxxx"
            ],
            "IpAddressType": "ipv4"
        }
    ]
}

HTTPSのリスナーの作成

実行コマンドの例

aws elbv2 create-listener 
--load-balancer-arn <ALB arn>
--protocol <Protocol Name>
--port <Port Number> 
--certificates <Certification arn>
--default-actions Type=forward,TargetGroupArn=<TargetGroupArn>

実行コマンドの結果

aws elbv2 create-listener --load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:loadbalancer/app/kmsn17-alb/xxxxxxxxxxxxxx --protocol HTTPS --port 443 --certificates CertificateArn=arn:aws:acm:ap-northeast-1:xxxxxxxxxxxxxxx:certificate/xxxxxxxxxxxxxxxxx --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxxx
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener/app/kmsn17-alb/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:loadbalancer/app/kmsn17-alb/xxxxxxxxxxxxxx",
            "Port": 443,
            "Protocol": "HTTPS",
            "Certificates": [
                {
                    "CertificateArn": "arn:aws:acm:ap-northeast-1:xxxxxxxxxxxxxxx:certificate/xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                }
            ],
            "SslPolicy": "ELBSecurityPolicy-2016-08",
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxxx",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxxxx",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ]
        }
    ]
}

送信元IPのルール作成

実行コマンドの例

aws elbv2 create-rule 
--listener-arn  <HTTPS Listener arn>
--priority  <Priority Number>
--conditions  <file://file name>
--actions Type=forward,TargetGroupArn= <TargetGroup Arn>

事前にファイルの作成が必要です。

[
  {
    "Field": "source-ip",
    "SourceIpConfig": {
        "Values": [
          "xxx.xxx.xxx.xxx/32"
        ]
    }
  }
]

実行コマンドの結果

aws elbv2 create-rule --listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener/app/kmsn17-alb/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxx --priority 20 --conditions file://ip-rule.js --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxxxxx
{
    "Rules": [
        {
            "RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxxxx",
            "Priority": "20",
            "Conditions": [
                {
                    "Field": "source-ip",
                    "SourceIpConfig": {
                        "Values": [
                            "xxx.xxx.xxx.xxx/32"
                        ]
                    }
                }
            ],
            "Actions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxx",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxx",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ],
            "IsDefault": false
        }
    ]
}

hostheaderの作成

実行コマンドの例

aws elbv2 create-rule 
--listener-arn <HTTPS Listener arn>
--priority <Priority Number>
--conditions <file://file name> 
--actions Type=forward,TargetGroupArn=<TargetGroup Arn>

事前にファイルの作成が必要です。

[
  {
      "Field": "host-header",
      "HostHeaderConfig": {
          "Values": ["hostheader名"]
      }
  }
]

実行コマンドの結果

aws elbv2 create-rule --listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener/app/kmsn17-alb/xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx --priority 10 --conditions file://hostheader.json --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxxxxxx
{
    "Rules": [
        {
            "RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxxx/xxxxxxxxxxxxx/xxxxxxxxxxxxx",
            "Priority": "10",
            "Conditions": [
                {
                    "Field": "host-header",
                    "Values": [
                        "xxxxxxx.cuebic-sre.work"
                    ],
                    "HostHeaderConfig": {
                        "Values": [
                            "xxxxxxx.cuebic-sre.work"
                        ]
                    }
                }
            ],
            "Actions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxx",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxx",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ],
            "IsDefault": false
        }
    ]
}

サブディレクトリの設定

実行コマンドの例

`aws elbv2 create-rule 
--listener-arn <HTTPS Listener arn>
--priority <Priority Number>
--conditions <file://file name>
--actions <file://file name> 
[
  {
      "Field": "path-pattern",
      "PathPatternConfig": {
          "Values": ["パスの設定"]
      }
  }
]

実行コマンドの結果

aws elbv2 create-rule --listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener/app/kmsn17-alb/xxxxxxxxxxxxxx/xxxxxxxxxxxxxxd --priority 30 --conditions file://pathpatter.json --actions file://text.json
{
    "Rules": [
        {
            "RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx",
            "Priority": "30",
            "Conditions": [
                {
                    "Field": "path-pattern",
                    "Values": [
                        "/test"
                    ],
                    "PathPatternConfig": {
                        "Values": [
                            "/test"
                        ]
                    }
                }
            ],
            "Actions": [
                {
                    "Type": "fixed-response",
                    "FixedResponseConfig": {
                        "MessageBody": "Not Found",
                        "StatusCode": "404",
                        "ContentType": "text/plain"
                    }
                }
            ],
            "IsDefault": false
        }
    ]
}

リスナールールの変更

実行コマンドの例

aws elbv2 modify-rule 
--actions Type=forward,TargetGroupArn=<TargetGroup Arn>
--conditions Field=host-header,Values='ValueName' Field=path-pattern,Values='ValueName' 
--rule-arn <HTTPS Listener Rule arn>

実行コマンドの結果

aws elbv2 modify-rule --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxx --conditions Field=host-header,Values='xxxxxxx.cuebic-sre.work' Field=path-pattern,Values='/images/*' --rule-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx
{
    "Rules": [
        {
            "RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxxxxxx",
            "Priority": "30",
            "Conditions": [
                {
                    "Field": "host-header",
                    "Values": [
                        "xxxxxxx.cuebic-sre.work"
                    ],
                    "HostHeaderConfig": {
                        "Values": [
                            "xxxxxxx.cuebic-sre.work"
                        ]
                    }
                },
                {
                    "Field": "path-pattern",
                    "Values": [
                        "/images/*"
                    ],
                    "PathPatternConfig": {
                        "Values": [
                            "/images/*"
                        ]
                    }
                }
            ],
            "Actions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxx",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxx",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ],
            "IsDefault": false
        }
    ]
}

ルールの優先順位の変更

実行コマンドの例

aws elbv2 set-rule-priorities 
--rule-priorities RuleArn=<HTTPS Listener Rule arn>,Priority=<Priority Number>

実行コマンドの結果

aws elbv2 set-rule-priorities --rule-priorities RuleArn=arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxxxxx,Priority=1
{
    "Rules": [
        {
            "RuleArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxx/xxxxxxxxxxx/xxxxxxxxxxx",
            "Priority": "1",
            "Conditions": [
                {
                    "Field": "source-ip",
                    "SourceIpConfig": {
                        "Values": [
                            "192.168.132.1/32"
                        ]
                    }
                }
            ],
            "Actions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxx",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxxx:targetgroup/kmsn17-alb-tg/xxxxxxxxxxxx",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ],
            "IsDefault": false
        }
    ]
}

ルールの削除

実行コマンドの例

aws elbv2 delete-rule 
--rule-arn <HTTPS Listener Rule arn>

実行コマンドの結果

aws elbv2 delete-rule 
--rule-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxxx:listener-rule/app/kmsn17-alb/xxxxxxxxxxx/xxxxxxxxxxx/xxxxxxxxxxx

所感

AWSCLIについて紹介しましたが、いかがでしたでしょうか?

僕も、元々コマンドが苦手でしたが今はALB構成のEC2構築、データ同期をScript化して自動構築したり、 Ansible、Terraformを使ってWebサーバの設定変更などを書いたりして、苦手意識がなくなり大変ご立派になってきました。笑

みなさんも、是非ゴリゴリにトライしてコマンドアレルギーをなくしましょう! それでは素敵なGWをお過ごしください。

参考文献

docs.aws.amazon.com

blog.serverworks.co.jp

qiita.com

dev.classmethod.jp

cloud5.jp