Data Sources in Detail

This lesson will teach you about Terraform data and how it is to used.

Terraform data source

A data source in Terraform is used to fetch data from a resource that is not managed by the current Terraform project. This allows it to be used in the current project. You can think of it as a read-only resource that already exists; the object exists, but you want to read specific properties of that object for use in your project.

Project example

Let’s dive into an example:

Press + to interact
provider "aws" {
region = "us-east-2"
}
data "aws_s3_bucket" "bucket" {
bucket = "kevholditch-already-exists"
}
resource "aws_iam_policy" "my_bucket_policy" {
name = "my-bucket-policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": [
"${data.aws_s3_bucket.bucket.arn}"
]
}
]
}
EOF
}

As you can see from the above project, a data source block starts with the word “data”. The next word is the type of data source. We are using an aws_s3_bucket data source, which is used to lookup an S3 bucket. After the data ...