This scenario shows:
- how to use Data Source to fetch/retrieve data (existed resource information) from AWS
Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/data-sources/main.tf
- You should have a look following lab:
- With data sources, existed resource information can be fetched/retrieved.
- "filter" provide to select/filter the existed instances
- "depends_on" provide to run the data block after resource created
...
data "aws_instance" "data_instance" {
filter {
name = "tag:Name"
values = ["Basic Instance"]
}
depends_on = [
aws_instance.instance
]
}
output "instance_info" {
value = data.aws_instance.data_instance
}
...
- Create main.tf:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "eu-central-1"
}
resource "aws_instance" "instance" {
ami = "ami-0d1ddd83282187d18" # Ubuntu 22.04 eu-central-1 Frankfurt
instance_type = "t2.nano"
tags = {
Name = "Basic Instance"
}
}
# filter/select the existed instances
# depends_on if aws_instance.instance is created
data "aws_instance" "data_instance" {
filter {
name = "tag:Name"
values = ["Basic Instance"]
}
depends_on = [
aws_instance.instance
]
}
output "instance_info" {
value = data.aws_instance.data_instance
}
output "instance_public_ip" {
value = data.aws_instance.data_instance.public_ip
}
Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/data-sources/main.tf
- Run init, validate command:
terraform init
terraform validate
- Run plan, apply command:
terraform plan
terraform apply
- With output, details can be viewed:
- Destroy infrastructure:
terraform destroy