Terraform - Data Sources in terraform resources

Namrata KumariNamrata Kumari
3 min read

Use of Data source in terraform code

Terraform Data Source:

  • The data sources allow terraform to use the information defined outside of terraform, defined by another separate terraform configuration or directly created in provider resources using another function.

  • Using data source is accessed via a special kind of resource known as a 'data resource', declared using a data block.

Data block:

Use case 1: Use of manually created golden ami in the data block

  • Below is the example data source block to filter the available AMIs from the AWS region and get the latest AMI as per the name filter.

data "aws_ami" "example" {
most_recent = true
owners = ["self"]
tags = {
Name = "app-server"
Tested = "true"
}
}

Steps to Create Golden Ami

  1. Create a normal ec2 instance

  2. Login to web-server

  3. Install Apache over there

  4. Check the status of apache2

  5. Go to Created Instance Actions> Image and templates > Create Image

  6. You can check the created AMI at 'Images'

  7. The custom ami you have created is pre-loaded with default configurations that you are expecting to be available on every instance in my project. This AMI called Golden AMI

  8. Now, go to the launch instance and create an instance by using custom ami.

  9. Launch the instance and see all created instance

  10. When I logged in to the tws-webserver and checked the status of apche2, it was running fine.

Use case2: Use of vpc resource from Terraform created state file

  • Below is the example data source block to get the explored variables from another terraform project remote state file.

data "terraform_remote_state" "vpc" {
backend = "s3"
config = {
bucket = "ed-k8s-config-data"
key = "dft/vpc/terraform.tfstate"
region = "us-east-1"
}
}

Task:

Write code to create an EC2 instance by use of existing Golden AMI and Terraform state-file.

Terraform Resources created:

S3-Backend-project

  1. dynamodb

  2. s3.tf

vpc-project

  1. backend.tf

  2. igw.tf

  3. output.tf

  4. priv-subnet.tf

  5. pub-subnet.tf

  6. rt.tf

  7. terraform.tfvars

  8. variables.tf

  9. vpc.tf

EC2-project

  1. backend.tf

  2. ec2.tf

  3. terraform.tfvars

  4. variables.tf

Run terraform project:

  1. S3-backend-project

  2. vpc-project

  3. EC2-project

Validate Output:

  1. s3 backend

  2. VPC

  3. EC2

Thank you for reading. Happy Learning😊

0
Subscribe to my newsletter

Read articles from Namrata Kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Namrata Kumari
Namrata Kumari

Proficient in a variety of DevOps technologies, including AWS, Linux, Python, Shell Scripting, Docker, Terraform, Kubernetes and Computer Networking.