Imran
Imran

Reputation: 1902

Terraform user data pass instance details

I need to set the host name & default network in the user data for my gcp instance with terraform, (user data template yml as below)

  serverInfo:
    serverId: 1
    hostname: ${hostname}
    defaultNetwork: ${defaultNetwork}

however, after some investigation I realized that this is quite difficult. As far as I understood, the user data is competed before the actual instance creation (correct me if wrong).But the hostname and network details will become available after the instance is created. Could you please suggest me a better way to capture that info and update it in user data?

Upvotes: 1

Views: 600

Answers (2)

Imran
Imran

Reputation: 1902

I found a way to fix the issue, so in case of network details, we can get hold of the network as below, and then extract the details about it such as cidr etc. For the host name however, we can specify the name in user data and the cloud-init will set the name for us.

   data "google_compute_subnetwork" "default-subnetwork" {
      project = "my-project"
      name   = "my-subnetwork"
      region = "us-central1"
    }

Upvotes: 0

Arcones
Arcones

Reputation: 4682

  • In case you have everything in one backend (you have one terraform state that manages everything), have you checked if any of the output parameters of the gcp instance is valid for your purpose? You can use them with a code snippet like in this examples:

google_compute_instance.name_of_your_instance.network_interface.0.network_ip

google_compute_instance.name_of_your_instance.self_link

  • If you have the gcp instance in a terraform backend different from the one in which you use the user data, maybe you can retrieve the details with terraform_remote_state (See more in https://www.terraform.io/docs/providers/terraform/d/remote_state.html). The nice thing is that this remote state is read only so nothing you do with it can affect your gcp instance.

Upvotes: 1

Related Questions