简体   繁体   中英

Terraform: How to pass output from one resource to another?

I'm using Aurora serverless Mysql and ECS and trying to use secrets generated by aws secret manager in a file named rds.tf and want to use it another resource in a file called ecs.tf

resource "random_password" "db_instance_aurora_password" {
  length  = 40
  special = false
  keepers = {
    database_id = aws_secretsmanager_secret.db_instance_aurora_master_password.id
  }

Above is rds.tf, which works and generates a random password. In my second file ecs.tf, I want to use the

resource "aws_ecs_task_definition" "task" {
  family = var.service_name
  container_definitions = templatefile("${path.module}/templates/task_definition.tpl", {
    DB_USERNAME  = var.db_username
    DB_PASSWORD  = random_password.db_instance_aurora_password.result
  })
}

How to export, the output of the db_password and use it in another resource(ecs.tf)?

output "aurora_rds_cluster.master_password" {
  description = "The master password"
   value    =  random_password.db_instance_aurora_password.result }
  1. If all terraform files are in one directory, you can just reference random_password resource as you do it for the database. Then you might not need to output it.

  2. If it's separated, then you can use terraform modules to achieve what you need. In ECS terraform you can reference RDS module and you will have access to its output:

module "rds" {
  source = "path/to/folder/with/rds/terraform"
}

resource "aws_ecs_task_definition" "task" {
  family = var.service_name
  container_definitions = templatefile("${path.module}/templates/task_definition.tpl", {
    DB_USERNAME  = var.db_username
    DB_PASSWORD  = module.rds.aurora_rds_cluster.master_password
  })
}
  1. Storing password in terraform's output will store it as a plain text. Even if you use encrypted S3 bucket, password can still be accessed at least by terraform. Another option to share password could be for example by using AWS Parameter Store. Module that creates password can store it in Param Store, and another module that needs a password can read it.

PS You might want to add sensitive = true to the password output in order to eliminate password value from logs.

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