Skip to content

Instantly share code, notes, and snippets.

@calexandre
Created December 4, 2022 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calexandre/3ff1e32260ce6730b50a29e50099e6cc to your computer and use it in GitHub Desktop.
Save calexandre/3ff1e32260ce6730b50a29e50099e6cc to your computer and use it in GitHub Desktop.
terraform code to get all GCP shared-vpc service-projects attached to a particular host-project
# instructions:
# on the first run you to target apply otherwise terraform will complain with for_each
# 1. terraform apply -target='null_resource.projects'
# 2. terraform apply
terraform {
required_providers {
google = {
source = "hashicorp/google"
}
}
}
variable "host_project_id" {
type = string
}
variable "projects_json_file" {
type = string
default = "./projects.json"
}
resource "null_resource" "projects" {
provisioner "local-exec" {
command = "gcloud compute shared-vpc list-associated-resources ${var.host_project_id} --format='json' > ${var.projects_json_file}"
}
}
data "local_file" "projects_json" {
filename = var.projects_json_file
}
data "google_project" "service" {
for_each = toset([for k in jsondecode(data.local_file.projects_json.content) : k.id])
project_id = each.key
}
output "service_projects" {
value = { for k, v in data.google_project.service : k => v.number }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment