首页 > 解决方案 > 如果 Terraform 的条件

问题描述

我正在尝试根据环境创建不同的规则

对于资源

资源“aws_lb_listener_rule”

如果 env == prod 那么 action { type = "redirect"

redirect {
  host = "${var.}"
  path = "/path"
  port = "443"
  protocol = "HTTPS"
  status_code = "HTTP_302"
}

否则动作{类型=“固定响应”

fixed_response {
  content_type = "path"
  status_code  = 503
  message_body = "${data.template_file.xxx_html.rendered}"
}

}

如何使用 terraform 实现这样的目标?

标签: terraformterraform-provider-aws

解决方案


中的一般方法terraform是使用资源count作为 if 语句来创建或不创建该场景中的资源。

aws_lb_listener_rule您可以将保留的资源的计数设置redirect1仅当environment变量设置为时的值prod

下面的例子有你想要的效果。

resource "aws_lb_listener_rule" "production_redirect_listener" {
  # Create this rule only if the environment variable is set to production
  count = var.environment == "prod" ? 1 : 0

  listener_arn = aws_lb_listener.arn
  action {
    type = "redirect"

    redirect {
      host = var.hostname
      path = "/path"
      port = "443"
      protocol = "HTTPS"
      status_code = "HTTP_302"
    }
  }
}

resource "aws_lb_listener_rule" "generic_fixed_response" {
  # If the environment variable is set to production do NOT create this rule
  count = var.environment == "prod" ? 0 : 1

  listener_arn = aws_lb_listener.arn
  action {
    type = "fixed-response"

    fixed_response {
      content_type = "path"
      status_code  = 503
      message_body = data.template_file.xxx_html.rendered
    }
  }
}

推荐阅读