Terraform Data Source

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:

#syntax
data "<resource_type>" "<name>"
{
  depends_on = ["<resource_type>.<resource_local_name>"]
    #resource dependencies that Terraform can"t automatically infer.
    #required only if dependent resource is not accessed by the resource
  count = <integer> 
    #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:

#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 = "<your_access_key>"
secret_key = "<your_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

#initialized 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

 

Leave a Reply

Close Menu