Terraform - Data Sources in terraform resources
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
Create a normal ec2 instance
Login to web-server
Install Apache over there
Check the status of apache2
Go to Created Instance Actions> Image and templates > Create Image
You can check the created AMI at 'Images'
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
Now, go to the launch instance and create an instance by using custom ami.
Launch the instance and see all created instance
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
dynamodb
s3.tf
vpc-project
backend.tf
igw.tf
output.tf
priv-subnet.tf
pub-subnet.tf
rt.tf
terraform.tfvars
variables.tf
vpc.tf
EC2-project
backend.tf
ec2.tf
terraform.tfvars
variables.tf
Run terraform project:
S3-backend-project
vpc-project
EC2-project
Validate Output:
s3 backend
VPC
EC2
Thank you for reading. Happy Learning😊
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.