data sources
Data sources let you read existing infrastructure without managing it - useful for referencing resources created outside Terraform or in another state file.
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["main"]
}
}
resource "aws_subnet" "app" {
vpc_id = data.aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
common data sources
# latest Amazon Linux 2 AMI
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
# current AWS account ID
data "aws_caller_identity" "current" {}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
# existing S3 bucket (not managed by this config)
data "aws_s3_bucket" "shared_logs" {
bucket = "my-shared-logs"
}
reading from another state file
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-tf-state"
key = "network/terraform.tfstate"
region = "us-east-1"
}
}
resource "aws_instance" "app" {
subnet_id = data.terraform_remote_state.network.outputs.private_subnet_id
ami = data.aws_ami.amazon_linux.id
}
data source vs resource
resource |
data |
|
|---|---|---|
| creates/modifies | yes | no |
| shows in plan | yes | no |
| can destroy | yes | no |
| reads on | apply | plan + apply |
Originally published at https://bard.sh/posts/terraform_data_sources/
Top comments (0)