Data Sources

Objective

Understand the basics of Terraform data sources.

Overview

We learned in the last section that providers can expose data sources for retrieving information. Data source declarations have four parts, the data keyword, the data source type, a name, and a configuration block.

data "type" "name" {}

Data sources make available attributes that can be access using the following syntax data.type.name.attribute.

Lab

In this lab we will utilize the HTTP provider to get data from an HTTP endpoint and use it in our project.

Add a Data Source

Edit main.tf

data "http" "tf_version" {
  url = "https://checkpoint-api.hashicorp.com/v1/check/terraform"

  request_headers = {
    Accept = "application/json"
  }
}

Add Another Output

Edit outputs.tf

output "data_source" {
  value = jsondecode(data.http.tf_version.response_body).current_version
}

Plan

Execute

terraform plan

Review

In this section we created a data source using the http provider to retrieve the latest version of Terraform from a Hashicorp API.

Additional Reading