How can I override a resource in a Terraform module?

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
}

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
}

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:

  • Version 0.12 and later (as of 19/10/2020).
  • Version 0.11 and earlier.

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
}

Tags:

Terraform