terraform

Terraform: how to access a resource in module for output?


How to access a resource for output, for exampe ec2 instance: aws_instance.splat_lab.ebs_block_device.*.volume_id Tried notation module.module-name.path-to-resource, i.e. module.webserver-cas12.aws_instance.splat_lab.ebs_block_device.*.volume_id but module.module-name is empty.

How to output from module or how to inbuild output of a speciific resource to module?


Solution

  • To properly output a specific resource, like an EC2 instance's volume_id, from a module in Terraform, here are some things you need to check:

    First, make sure the module itself defines the output you need. You can define the output for the volume_id in the outputs.tf file within the module.

    output "ebs_volume_ids" {
      value = aws_instance.splat_lab.ebs_block_device.*.volume_id
    }
    

    This will output all the volume_ids associated with the ebs_block_device of the EC2 instance resource inside the module.

    In your root module (where you call the module), you can reference this output using the following syntax:

    module "webserver" {
      source = "./path-to-your-module"
    
      # Other variables you may pass to the module
    }
    
    output "webserver_ebs_volume_ids" {
      value = module.webserver.ebs_volume_ids
    }
    

    Make sure the module name (webserver) matches the name you use in your module block.

    Notes based on your specific situation: