简体   繁体   中英

How can I override a resource in a Terraform module?

I've got a Terraform module like this:

module "helloworld" {
  source = "../service"
}

and ../service contains:

resource "aws_cloudwatch_metric_alarm" "cpu_max" {
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "2"
  ... etc
}

How do you override the service variables comparison_operator and evaluation_periods in your module?

Eg to set cpu_max to 4 is it as simple as aws_cloudwatch_metric_alarm.cpu_max.evaluation_periods = 4 in your module?

You have to use a variable with a default value.

variable "evaluation_periods" {
    default = 4
}

resource "aws_cloudwatch_metric_alarm" "cpu_max" {
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "${var.evaluation_periods}"
}

And in your module

module "helloworld" {
  source = "../service"
  evaluation_periods = 2
}

you'll have to define variables in your module. Your module would be:

variable "eval_period" {default = 2} # this becomes the input parameter of the module

resource "aws_cloudwatch_metric_alarm" "cpu_max" {
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "${var.eval_period}"
  ... etc
}

and you'd use it like:

module "helloworld" {
  source = "../service"
  eval_period = 4
}

In addition to the other answers using variables:

If you want to override the whole resource or just do a merge of configuration values, you can also use the overriding behaviour from Terraform:

Using this feature you could have a file named service_override.tf with the content:

resource "aws_cloudwatch_metric_alarm" "cpu_max" {
   comparison_operator = "LessThanThreshold"
   evaluation_periods  = "4"
   ... etc
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM