terraform data - ghdrako/doc_snipets GitHub Wiki
https://www.terraform.io/docs/configuration/data-sources.html https://registry.terraform.io/providers/hashicorp/google/latest/docs https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/project https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/client_config
Terraform data sources allow you to extract output or information from already existing resources that got provisioned by any other Terraform configuration, or manually or by any other means.
# Get output from existing resource
data "azurerm_virtual_network" "example" {
name = "production-vnet"
resource_group_name = "Terraform-rg"
}
output "virtual_network_id" {
value = data.azurerm_virtual_network.example.id
}
# create a subnet in the existing virtual network
data "azurerm_resource_group" "example" {
name = "Terraform-rg"
}
data "azurerm_virtual_network" "example" {
name = "production-vnet"
resource_group_name = data.azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "terraform-subnet"
resource_group_name = data.azurerm_resource_group.example.name
virtual_network_name = data.azurerm_virtual_network.example.name
address_prefixes = ["10.0.1.0/24"]
}
# defined vpc_id as an input variable
variable "vpc_id" {}
data "aws_vpc" "example" {
id = var.vpc_id
}
resource "aws_subnet" "example" {
vpc_id = data.aws_vpc.example.id
availability_zone = "us-west-2a"
cidr_block = cidrsubnet(data.aws_vpc.example.cidr_block, 4, 1)
}
data "google_compute_instance" "example" {
name = "Terraform-server"
zone = "us-central1-a"
}
GCP
The project number is found in the google_project data-source (https://www.terraform.io/docs/providers/google/d/project.html).
So when this one is added:
data "google_project" "project" {}
project number should be accessible using:
data.google_project.project.number
use google_client_config data-source to access the configuration of the provider.
First, add the following data-source block to main.tf:
data "google_client_config" "current" {}
Then, you would be able to access the project_id as below:
output "project_id" {
value = data.google_client_config.current.project
}
For more information, please refer to: https://www.terraform.io/docs/providers/google/d/client_config.html
Share