简体   繁体   中英

Terraform: How to use key value output

I've researched a possible solution for my problem, but it seems mine is more specific.

So, I've a resource aws_kms_key which is created by for_each expression:

for_each = { for keys in var.parameters : keys.name => keys if local.secrets.init.self == true }

Nothing specific, everything is working fine, however I don't know how to use an output arn of created key. Here is my output:

output "key" {
   description = "The 'Amazon Resource Name (ARN)' of 'KMS' key(s)"
   value       = zipmap( 
     values(aws_kms_alias.global)[*].name, values(aws_kms_key.global)[*].arn
   )
}

I've used before for expression but in that case, I have to use index to allocate the arn of kms key, which is obviously not good even not acceptable practice. Here is my old output way:

output "key" {
   description = "The 'Amazon Resource Name (ARN)' of 'KMS' key(s)"
   value       = [ for key, value in aws_kms_key.global : value.arn ]
}

Usage

flowlog_encryption  = [{
  keys            = element(module.secrets.*.key, 0)[0]
  retention       = 14
}]

The problem with "old" way is, when resource is created I can access only with index, and when something is changing, the orders of index is changing too, so when I'm creating a key for dynamodb and flowlogs the dynamodb took key of flowlogs and flowlogs tooks key of dynamodb , completely random behaviour.

Your new output key , the one where zipmap is used, is going to produce a map with keys of alias name, and the corresponding values of keys arn. This will be something as follows:

output "key" {
   description = "The 'Amazon Resource Name (ARN)' of 'KMS' key(s)"
   value       = {
        alias_name1 = key_arn1
        alias_name2 = key_arn2
        alias_name3 = key_arn3
   }
}

Assuming that module.secrets.key is your output key above, you would use it as follows:

flowlog_encryption  = [{
  keys            = module.secrets.key["alias_name1"]
  retention       = 14
}]

or with lookup :

flowlog_encryption  = [{
  keys            = lookup(module.secrets.key, "alias_name1", "default_key_arn")
  retention       = 14
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM