Terraform现在能更简洁地编写ALB的高级监听规则

你好,我是七七。
大家有在使用Terraform吗?顺便说一下,最近我开始接触Terraform了。
今天我想写一下关于Terraform的AWS提供商的更新,因为在2019年12月14日进行了更新,我马上试了试。

首先

Terraform是由HashiCorp创建的开源工具,用于实现基础设施即代码(Infrastructure as Code)。

应用负载均衡器(ALB)是什么

component_architecture.png

关于听众规则

在ALB中,根据听众规则来控制来自用户的流量。

2019年3月27日,AWS进行了监听规则的扩展。详情请参考。

    • Application Load Balancer で高度なリクエストルーティングのサポートを開始

 

    [新機能] HTTPヘッダーやクエリ文字列などなどでルーティングができちゃう!!AWS ALBで高度なリクエストルーティングが可能になりました! | Developers.IO

正如所述,现在可以使用请求头中的用户代理等值来进行更灵活的路由。

在编写Terraform时

通过AWS提供的服务,将负责管理各种AWS资源。关于上述扩展的详细内容如下所述:

resource "aws_lb_listener_rule" "http_header_based_routing" {
  listener_arn = aws_lb_listener.front_end.arn
  priority = 10

  action {
    type = "forward"
    target_group_arn = aws_lb_target_group.tg.arn
  }

  condition {
    http_header {
      http_header_name = "User-Agent"
      values           = [
        "*Chrome*",
        "*Safari*",
      ]
    }
  }
}

在输入`terraform plan`或`terraform apply`时,出现了以下错误。

Error: Unsupported block type

  on elb.tf line xx, in resource "aws_lb_listener_rule" "http_header_based_routing":
  xx:     http_header {

Blocks of type "http_header" are not expected here.

因此,我在尋找一種能夠有效地撰寫的方式時,查看了AWS提供商的存儲庫。結果我找到了相關的拉取請求,但該請求目前為開啟狀態(現在已關閉)。總而言之,看起來仍然有待處理。

然后,时间过去了,它在2019年12月7日被合并到主分支。然后,在2019年12月14日以2.42.0的版本发布了。

顺便说一下,在 Terraform 可以更简洁地编写之前,我们需要使用 Terraform 创建 CloudFormation 堆栈来进行管理。如果没有遗忘,我想我会在某篇文章中详细介绍。可能已经有人写了,可能会成为一个二手来源……

试试使用Terraform来编写高级ALB监听规则。

我会根据这个参考为AWS提供商提供2.42.0版本的二进制文件。

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.42.0...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

本次我们将尝试实现用于判断Chrome和Safari浏览器的监听规则。请查看此处以了解其他方式。

resource "aws_lb_listener_rule" "http_header_based_routing" {
  listener_arn = aws_lb_listener.front_end.arn
  priority = 10

  action {
    type = "forward"
    target_group_arn = aws_lb_target_group.tg.arn
  }

  condition {
    http_header {
      http_header_name = "User-Agent"
      values           = [
        "*Chrome*",
        "*Safari*",
      ]
    }
  }
}

使用terraform plan和terraform apply来确认内容后进行部署。

スクリーンショット 2019-12-14 11.21.09.png

就是这样。

最后

虽然花费了8个月以上才合并,但ALB的高级监听规则现在可以更简洁地使用Terraform编写。大家一定要试一试。

广告
将在 10 秒后关闭
bannerAds