Terraform Data Source
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed terraform variable file.
https://cloudaffaire.com/terraform-variable-file/
In this blog post, we will discuss terraform data source.
What is Terraform data source?
Data sources allow data to be fetched or computed for use elsewhere in Terraform configuration. Use of data sources allows a Terraform configuration to build on information defined outside of Terraform, or defined by another separate Terraform configuration.
Data Source Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## Syntax data " { depends_on = [" #resource dependencies that Terraform can"t automatically infer. #required only if dependent resource is not accessed by the resource count = #for multiple resource creation provider = <"provider.alias"> #for selecting non default provider (provider with alias) provisioner and connection #for taking extra actions after resource creation } |
Data Source demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
##---------------------------- ## Terraform: Data Source ## ##---------------------------- ## Create a directory and get inside it mkdir terraform && cd terraform ## Create main.tf vi main.tf --------------- #Create a VPC with subnets in each availability zones provider "aws" { access_key = " secret_key = " region = "ap-south-1" } # Declare a data source (fetches AZ’s details) data "aws_availability_zones" "availability_zones" {} resource "aws_vpc" "myvpc" { cidr_block = "10.0.0.0/16" tags { Name = "myvpc" } } resource "aws_subnet" "myvpc_subnets" { count = "${length(data.aws_availability_zones.availability_zones.names)}" #returns number of AZ's vpc_id = "${aws_vpc.myvpc.id}" cidr_block = "${cidrsubnet("${aws_vpc.myvpc.cidr_block}",8,count.index+1)}" availability_zone = "${element(data.aws_availability_zones.availability_zones.names,count.index)}" #returens AZ's name tags { Name = "myvpc_subnet_${count.index+1}" } } ---------------- :wq ## Format code terraform fmt ## Initialize terraform terraform init ## Create the resource terraform apply #Login to AWS console and check VPC, subnet ## Destroy the resources terraform destroy ## Cleanup cd .. && rm -rf terraform |
Hope you have enjoyed this article. In the next blog post, we will discuss terraform output.
To get more details on terraform, please refer below terraform documentation
https://www.terraform.io/docs/index.html