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
-
vpc-project
-
-
-
-
-
-
terraform.tfvars
-
-
EC2-project
-
-
terraform.tfvars
Run terraform project:
S3-backend-project
vpc-project
EC2-project
Validate Output:
s3 backend
VPC
EC2
Thank you for reading. Happy Learning😊