Aug 10, 2023 1 min read

Terraform - How to output a value to the CLI from a child module

Terraform - How to output a value to the CLI from a child module
Table of Contents

The problem with outputs created within a child module is that they are not immediately accessible from the root module. So, a terraform apply (run from the root directory) will not output the values to the CLI by default.

To accomplish that we would need a second output—one written in the root module that calls on the output in the child module.

This video shows how to configure it so that the output in the child module is displayed in the terminal. See below for video and code.


I'm working with IAM users here because they build quickly and cost nothing (at least in my region as of the writing of this post).

Directory/file structure

./tf-test
  main.tf
  /users_module
    users.tf

main.tf

# main.tf (within the main working directory/root module)

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  required_version = ">= 1.3.6"
}

provider "aws" {
  region = "us-east-2"
}


module "users_module" {
  source = "./users-module"
}

output "user_names" {
  value = module.users_module.name_of_all_users
}

users.tf

# users.tf (within the users_module child module/directory)

resource "aws_iam_user" "test_user" {
  name  = "person-${count.index}"
  count = 3
  tags = {
    time_created = timestamp()
    department   = "OPS"    
  }
}

output "name_of_all_users" {
  value = aws_iam_user.test_user[*].name
}
💡
Remember that the outputs in the root and child module are not the same. One calls on the other to display the value to the CLI:
root module output > child module output > CLI
Excellent.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Prowse Tech.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.