'Terraform conditionally create resource based on whether a map key exists

I am creating a file in a bucket based on a value stored in Vault. The vault provider pulls the information in as a map, and the key "MESSAGING_KEY" has a block of text as it's value which gets dropped in to the file.

I only want this resource to get created if the key exists, as otherwise I get an error message. I came up with the following:

resource "aws_s3_bucket_object" "messaging-key" {
  count  = can(data.vault_generic_secret.vault-keys-secrets.data["MESSAGING_KEY"]) ? 1 : 0
  bucket = module.keys.s3_bucket_id
  key    = "messaging.pem"
  content = data.vault_generic_secret.vault-keys-secrets.data["MESSAGING_KEY"]

  etag = md5(data.vault_generic_secret.vault-keys-secrets.data["MESSAGING_KEY"])
}

Is there a better way of achieving this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source