terraform-google-kubernetes-engine icon indicating copy to clipboard operation
terraform-google-kubernetes-engine copied to clipboard

Consider using provider-defined functions to simplify data transformations in modules

Open SarahFrench opened this issue 1 year ago • 0 comments

Hi there!

In v5.23.0 of the google (and google-beta) provider we introduced our first provider-defined functions.

For more information on provider-defined functions please see the Terraform 1.8 announcement blog, and a blog about the provider-defined functions released so far in major providers.

There is also the official documentation for provider-defined functions.

v5.23.0 of the Google providers for Terraform included these functions:

  • region_from_zone - when passed a zone name as an argument it'll return the containing region's name
  • project_from_id - when passed a resource's id or self link as an argument it'll look for projects/{{project}} in that input and return the resource's containing project
  • name_from_id - when passed a resource's id or self link as an argument it'll return the last element in the identifier, e.g. "my-instance" is derived from "projects/my-project/zones/us-central1-c/instances/my-instance"
  • location_from_id - when passed a resource's id or self link as an argument it'll look for locations/{{location}} in that input and return the resource's location
  • region_from_id - same as above but regions/{{region}} and returns the resource's region
  • zone_from_id - same as above but zones/{{zone}} and returns the resource's zone

Considerations

Some examples of where these could be used in modules

region_from_zone

https://github.com/terraform-google-modules/terraform-google-kubernetes-engine/blob/15b472fafc6b63afb0b52acec56cea8fd5c25cdf/main.tf#L44

 region   = var.regional ? var.region : provider::google::region_from_zone(var.zones[0])

location_from_id

https://github.com/terraform-google-modules/terraform-google-kubernetes-engine/blob/15b472fafc6b63afb0b52acec56cea8fd5c25cdf/modules/fleet-membership/main.tf#L21-L22

 gke_hub_membership_location      = try(provider::google::location_from_id(data.google_container_cluster.primary.fleet[0].membership[0]), null) 

SarahFrench avatar Apr 11 '24 12:04 SarahFrench