Search code examples
google-cloud-platformterraformterraform-provider-gcp

Terraform `name` vs `self_link` in GCP


In GCP, when using Terraform, I see I can use name attribute as well as self_link. So, I am wondering if there are cases where I must use any of those.

For example:

resource "google_compute_ssl_policy" "custom_ssl_policy" {
  name            = "my-ssl-policy"
  profile         = "MODERN"
  min_tls_version = "TLS_1_1"
}

this object, then can be referred as:

ssl_policy = google_compute_ssl_policy.custom_ssl_policy.name

and

ssl_policy = google_compute_ssl_policy.custom_ssl_policy.self_link

I know that object.name returns the Terraform object name, and object.self_link returns GCP's resources's URI.

I have tried with several objects, and it works with both attributes, so I want to know if this is trivial or there are situations where I should use one of them.


Solution

  • Here is the definition from the official documentation:

    Nearly every GCP resource will have a name field. They are used as a short way to identify resources, and a resource's display name in the Cloud Console will be the one defined in the name field.

    When linking resources in a Terraform config though, you'll primarily want to use a different field, the self_link of a resource. Like name, nearly every resource has a self_link. They look like:

    https://www.googleapis.com/compute/v1/projects/foo/zones/us-central1-c/instances/terraform-instance

    A resource's self_link is a unique reference to that resource. When linking two resources in Terraform, you can use Terraform interpolation to avoid typing out the self link!

    Reference: https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started

    One example, I can deploy two cloud functions with the same name/same project but in different regions. In this case, if you had to reference both resources in Terraform code, you would be better by using the self_link since it's a unique URI.