user3785023
user3785023

Reputation: 39

If condition for Terraform

I am trying to create different rules based on the environment

for the resource

resource "aws_lb_listener_rule"

if env == prod then action { type = "redirect"

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

else action { type = "fixed-response"

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

}

how can I achieve something like this using terraform ?

Upvotes: 2

Views: 8937

Answers (1)

Mihai Stancu
Mihai Stancu

Reputation: 434

The general approach in terraform is to use resource count as an if statement to create or not the resource in that scenario.

You can set the count of the aws_lb_listener_rule resource that will hold the redirect to a value of 1 only if the environment variable is set to prod.

The following example has the effect you desire.

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
    }
  }
}

Upvotes: 2

Related Questions