Terraform: Use default variable if parameter store value doesn't exist

Viewed 15

Overview

  • using Terraform cloud.
  • seed variable "environment" specified in Terraform cloud workspace e.g dev/test/prod
  • The "environment" variable is used to look up values in AWS parameter store e.g.
data "aws_ssm_parameter" "rds_password" {
  name = "/${var.environment}/rds/pg/rds_password"
}

module "db" {
  password               = data.aws_ssm_parameter.rds_password.value
}

Question

What's the best way to go about setting default values? It seems as though using locals to check for the existence of the parameter otherwise use the default var.

Thanks in advance for any pointers.

1 Answers

You could probably use the try built-in function [1]. For example:

module "db" {
  password = try(data.aws_ssm_parameter.rds_password.value, local.rds_password)
}

As you have mentioned, you would of course have to provide a local or a normal variable. If you decide for the latter, you would have to either provide the value when running plan/apply or a default one.


[1] https://developer.hashicorp.com/terraform/language/functions/try

Related