SiddhiMorajkar
SiddhiMorajkar

Reputation: 425

Cannot get the outputs when terraform output is run

I am making use of modules. And this is the structure of my files - Provisioner and module are different folders.The main.tf in stack calls out the modules.

  > provisioner 
        >stack
           |--main.tf
           |--variables.tf
  > module (folder)  
    |--aks
    |     |--main.tf
    |     |--outputs.tf
    |     |--variables.tf
    |
    |--postgresql
    |     |--main.tf
    |     |--outputs.tf
    |     |--variables.tf

When i run "terraform apply" command in the provsioner directory,it is expected to return the outputs after the apply is done. I dont get outputs. When i run 'terraform output' i get- "The state file either has no outputs defined, or all the defined outputs are empty. Please define an output in your configuration with the output keyword and run terraform refresh for it to become available. If you are using interpolation, please verify the interpolated value is not empty"

I would want to know why is this happening?

Upvotes: 5

Views: 22214

Answers (4)

ccoutinho
ccoutinho

Reputation: 4534

I was getting this error because I was running terraform output from outside the terraform folder, whereas this command must be executed from the same directory where terraform apply was executed.

The commands below make sure that is the case.

terraform -chdir="$TF_PROJECT_PATH" apply -input=false -auto-approve

terraform -chdir="$TF_PROJECT_PATH" output

Upvotes: 0

crewy_stack
crewy_stack

Reputation: 560

Terraform 0.12 and later intentionally track only root module outputs in the state. To expose module outputs for external consumption, you must export them from the root module using an output block, which as of 0.12 can now be done for a single module all in one output, like this:

output "example_module" {
  value = module.example_module
}

So for your code, add a output.tf file in the root and then add output statement whichever you need output after apply.

Github issue : https://github.com/hashicorp/terraform/issues/22126

Upvotes: 19

Zarrao Zaga
Zarrao Zaga

Reputation: 189

Adding on to @crewy_stack answer. let's say your module is named as sample_ec2_mod. Inside the module directory ensure that the outputs are specified in outputs.tf

On the main.tf in the root folder, add the following:

module "sample_ec2_mod" {
    source = "./ec2"  
}
  
output "ec2_module" {  
  value = module.sample_ec2_mod  
}

When you enter terraform apply in your cli, it should give you an output option. After applying, simply use terraform output to see the outputs.

Upvotes: 10

dmkvl
dmkvl

Reputation: 768

Output vars of modules won't be printed out by default. You have to explicitly define the output vars in your provisioner dir.

Upvotes: 6

Related Questions