user389955
user389955

Reputation: 10487

how to print private IP from the module created using terraform-google-modules

I have created some gcp instances using terraform module:

module "instance_template" {
  source = "terraform-google modules/vm/google//modules/instance_template"
...
}
module "compute_instance" {
  source             = "terraform-google- 
   modules/vm/google//modules/compute_instance"
  num_instances      = 4
  ...
}

then how do I get and output the private ip of these 4 instances after I run terraform apply?

Upvotes: 1

Views: 1470

Answers (2)

Shabirmean
Shabirmean

Reputation: 2571

The module outputs instances_details from which you can get the ip addresses.

Below is an example to get the IPs of all the instances created

output "vm-ips" {
  value = flatten(module.compute_instance[*].instances_details.*.network_interface.0.network_ip)
}

Output:

vm-ips = [
  "10.128.0.14",
  "10.128.0.15",
  "10.128.0.16",
]

In you had repeated the module with for-each to create groups of instances with different params.

  • Say 2 instances each with hostname starting with some prefix in 2 groups

Then, you can get all their IPs as follows:

output "vm-ips" {
  value = flatten([
     for group in module.compute_instance[*] : [
      for vm_details in group: [
        for detail in vm_details.instances_details: {
          "name" = detail.name
          "ip" = detail.network_interface.0.network_ip
        }
      ]
     ]
  ])
}

Output:

vm-ips = [
  {
    "ip" = "10.128.0.17"
    "name" = "w1-001"
  },
  {
    "ip" = "10.128.0.18"
    "name" = "w1-002"
  },
  {
    "ip" = "10.128.0.20"
    "name" = "w2-001"
  },
  {
    "ip" = "10.128.0.19"
    "name" = "w2-002"
  },
]

Upvotes: 2

Vikram Shinde
Vikram Shinde

Reputation: 1028

This module does not have output as private Ips. It has only outputs instances_self_links and available_zones

Better to use, resource block of google_compute_instance_template and google_compute_instance_from_template

Then you can use output block to fetch all 4 private ips

output {
value = google_compute_instance_from_template.instances[*].network_ip
}

Upvotes: 2

Related Questions