In simple words Terraform Data Source is:
- Bridge between “Terraform-created” and “non-Terraform-created” infrastructure
- A Terraform data source lets you query or fetch existing information from outside Terraform so you can use it inside your Terraform configuration.
Let me give an example:
Let's say you have an existing VPC created but not managed by terraform, now you want to create a EC2 in that VPC, so you need the VPC info, in such scenario you can use Data Source.
Also when value of particular resource changes dynamically, like AMI id, we can use Data Source
One thing to remember about Data Source
- using Data Source we cannot create resources.
- we can reference existing resources, fetch dynamic info.
Example
- using existing VPC configuration
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["main-vpc"]
}
}
resource "aws_subnet" "app" {
vpc_id = data.aws_vpc.main.id
}
- Getting latest AMI id
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["main-vpc"]
}
}
resource "aws_subnet" "app" {
vpc_id = data.aws_vpc.main.id
}
Benifits of using Data Source
- Eleminating of HardCoding.
- Enable modular, resuable code
Video:
Top comments (0)