CallumVass
CallumVass

Reputation: 11448

Terraform - Optional SSM parameter lookup

I'm doing a lookup for an SSM parameter which may or may not exist depending on a variable passed in:

data "aws_ssm_parameter" "server_tags" {
  name  = "/${var.env_number}/server_tags"
}

I am then using it like below in my locals and passing to my module:

locals {
  server_tags = data.aws_ssm_parameter.server_tags != null ? jsondecode(data.aws_ssm_parameter.server_tags.value) : {}
  instance_tags = merge(var.instance_tags, local.server_tags)
}

This works fine when my parameter exists, but if I pass in a value where my parameter doesn't exist, I get an error:

Error describing SSM parameter (/997/server_tags): ParameterNotFound: 

Is there anyway I can do a pre-check to see if the parameter exists or make it optional somehow?

Thanks

Upvotes: 4

Views: 5298

Answers (2)

dubsauce
dubsauce

Reputation: 43

With Terraform 1.5.4 I was able to use a count with aws_ssm_parameter:

data "aws_ssm_parameter" "bucket_name" {
  count = var.bucket_name_ssm_path == "none" ? 0 : 1
  name = var.bucket_name_ssm_path
}

variable "bucket_name_ssm_path" {
  type        = string
  default     = "none"
}

locals {
  bucket_name = var.bucket_name_ssm_path == "none" ? null : data.aws_ssm_parameter.bucket_name[0].value
}

My module also uses bucket_prefix or bucket_name = local.bucket_name and it seems to work. I'm not sure if this is a new feature of Terraform, I know for sure it didn't work in the past.

Upvotes: 0

Marcin
Marcin

Reputation: 238209

Sadly you can't do this. There is no way build-on mechanism for TF to check if a data source exists or not. But you can program your own logic for that using External Data Source.

Since you program the external data source, you can create a logic for checking if a resource exists or not.

Upvotes: 4

Related Questions