Home > Net >  How to get internal ip of postgreSQL DB in GCP created by Terraform
How to get internal ip of postgreSQL DB in GCP created by Terraform

Time:07-17

I am learning terraform deployments coupled with GCP to streamline deployments.

I have successfully deployed a postgreSQL db.

Now I am trying to utilize terraform outputs to write a the private ip generated by the postgreSQL DB server to the output directory where terraform is initiated from. What is not clear to me is:

(1) The output is defined within the same main.tf file?

(2) Where is the output parameters referenced from? I cannot find the documentation to properly aline. Such I keep getting the error upon applying: Error: Reference to undeclared resource

My main.tf looks like this

resource "google_sql_database_instance" "main" {
  name             = "db"
  database_version = "POSTGRES_12"
  region           = "us-west1"

  settings {
    availability_type = "REGIONAL"
    tier = "db-custom-2-8192"
    disk_size = "10"
    disk_type = "PD_SSD"
    disk_autoresize = "true"
  }
}

output "instance_ip_addr" {
  value       = google_sql_database_instance.private_network.id
  description = "The private IP address of the main server instance."
}

CodePudding user response:

As for the code style, usually there would be a separate file called outputs.tf where you would add all the values you want to have outputted after a successful apply. The second part of the question is two-fold:

  1. You have to understand how references to resource attributes/arguments work [1][2]
  2. You have to reference the correct logical ID of the resource, i.e., the name you assigned to it, followed by the argument/attribute [3]

So, in your case that would be:

output "instance_ip_addr" {
  value       = google_sql_database_instance.main.private_ip_address # <RESOURCE TYPE>.<NAME>.<ATTRIBUTE>
  description = "The private IP address of the main server instance."
}

[1] https://www.terraform.io/language/expressions/references#references-to-resource-attributes

[2] https://www.terraform.io/language/resources/behavior#accessing-resource-attributes

[3] https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/sql_database_instance#attributes-reference

CodePudding user response:

To reference an attribute of a resource, you should put something like:

[resource type].[resource name].[attribute]

In this case, the output should be:

output "instance_ip_addr" {
  value       = google_sql_database_instance.main.private_ip_address
  description = "The private IP address of the main server instance."
}

The output attributes are listed in the documentation. It's fine to put that in main.tf.

  • Related