Home > database >  if else condiation on key name in terraform codes
if else condiation on key name in terraform codes

Time:10-14

as I knew, we can use terraform count as if-else condiation, but that's for value.

Use sample of Data Source: aws_secretsmanager_secret

It has two keys: name or arn

My condiation is,

  • if I got variable secret_name, it will use key name
  • if I got variable secret_arn, it will use key arn
  • they can't bevused at same time (I can't control this by myself)

how to do that, something like this

data "aws_secretsmanager_secret" "by-arn" {
  if count = length(var.secret_arn)
     arn = var.secret_arn
  else if count = length(var.secret_name)
     name = var.secret_name
  fi
}

CodePudding user response:

You can alternate between arn and name as follows:

data "aws_secretsmanager_secret" "by-arn" {
  arn = length(var.secret_arn) > 0 ? var.secret_arn : null
  name = length(var.secret_name) > 0 ? var.secret_name : null
}

CodePudding user response:

For aws_secretsmanager_secret you can specify only arn or name, so you would need two data objects using count.

data "aws_secretsmanager_secret" "by_arn" {
  count = length(var.secret_arn) > 0 ? 1 : 0
  arn   = var.secret_arn
}

data "aws_secretsmanager_secret" "by_name" {
  count = length(var.secret_name) > 0 ? 1 : 0
  name  = var.secret_name
}

If you want to ensure only one of both variable is used, you'll need some workaround using locals, see Terraform - ensure value is set depending on if another value is also set

  • Related