Query data sources
Terraform data sources let you dynamically fetch data from APIs or other Terraform state backends. Examples of data sources include machine image IDs from a cloud provider or Terraform outputs from other configurations. Data sources make your configuration more flexible and dynamic and let you reference values from other configurations, helping you scope your configuration while still referencing any dependent resource attributes. In HCP Terraform, workspaces let you share data between workspaces.
In this tutorial, you will use data sources to make your configuration more
dynamic. First, you will use Terraform to create an AWS VPC and security groups.
Next, you will use the aws_availability_zones
data source to make your
configuration deployable across any region. You will then deploy application
infrastructure defined by a separate Terraform configuration, and use the
terraform_remote_state
data source to query information about your VPC.
Finally, you will use the aws_ami
data source to configure the correct AMI for
the current region.
Prerequisites
You can complete this tutorial using the same workflow with either Terraform Community Edition or HCP Terraform. HCP Terraform is a platform that you can use to manage and execute your Terraform projects. It includes features like remote state and execution, structured plan output, workspace resource summaries, and more.
This tutorial assumes that you are familiar with the Terraform workflow. If you are new to Terraform, complete Get Started collection first.
For this tutorial, you will need:
- Terraform v1.2+ installed locally.
- the AWS CLI.
- AWS Credentials configured for use with Terraform.
Note
Some of the infrastructure in this tutorial may not qualify for the AWS free tier. Destroy the infrastructure at the end of the guide to avoid unnecessary charges. We are not responsible for any charges that you incur.
Clone example repositories
The example configuration for this tutorial is hosted in two GitHub repositories.
The VPC repository contains the configuration to deploy a VPC and security groups for your application.
Clone the VPC repository.
The application repository contains the configuration to deploy an example application consisting of a load balancer and an EC2 instance.
Clone the application repository.
Initialize VPC workspace
Change to the VPC repository directory.
Open your terraform.tf
file and comment out the cloud
block that configures
the HCP Terraform integration.
Initialize your configuration.
Update VPC region
The VPC configuration uses a variable called aws_region
with a default value
of us-east-1
to set the region.
However, changing the value of the aws_region
variable will not successfully
change the region because the VPC configuration includes an azs
argument to
set Availability Zones, which is a hard-coded list of availability zones in the
us-east-1
region.
Use the aws_availability_zones
data source to load the available AZs for the
current region. Add the following to main.tf
.
The
aws_availability_zones
data source is part of the AWS provider and retrieves a list of availability zones based on the arguments supplied. In this case, the state
argument limits the availability zones to only those that are currently available.
You can reference data source attributes with the pattern
data.<NAME>.<ATTRIBUTE>
. Update the VPC configuration to use this data source
to set the list of availability zones.
Configure the VPC workspace to output the region, which the application
workspace will require as an input. Add a data source to main.tf
to access
region information.
Add an output for the region to outputs.tf
.
Create infrastructure
Apply this configuration, setting the value of aws_region
to us-west-1
.
Respond to the confirmation prompt with a yes
.
Tip
In this scenario, you could use the aws_region
variable to define
the output parameter instead of using the data source. However, there are
multiple ways to configure the AWS region. Using the aws_region
data source
will get the AWS provider's current region no matter how it was configured.
Configure Terraform remote state
Now that you deployed your network resources, go to the
learn-terraform-data-sources-app
directory.
This directory contains the Terraform configuration for your application.
Open your terraform.tf
file and comment out the cloud
block that configures
the HCP Terraform integration.
Initialize your configuration.
Like the VPC workspace, this configuration includes hard-coded values for the
us-east-1
region. You can use the
terraform_remote_state
data source to use another Terraform workspace's output data.
Add a terraform_remote_state
data source to the main.tf
file inside the
learn-terraform-data-sources-app
directory, replacing YOUR_ORG
with your own HCP Terraform organization name.
This remote state block uses the local backend to load state data
from the path in the config
section. Terraform remote state also supports a
remote backend type for use with remote
systems,
such as HCP Terraform or Consul.
Now, update your aws
provider configuration in main.tf
to use the same region as the VPC configuration instead of a hardcoded region.
The VPC configuration also included outputs for subnet and security group IDs. Configure the load balancer security group and subnet arguments for the elb
module with those values.
Note
Terraform's remote state data source can only load "root-level" output values from the source workspace, it cannot directly access values from resources or modules in the source workspace. To retrieve those values, you must add a corresponding output to the source workspace.
Scale EC2 instances
You can use values from data sources just like any other Terraform values,
including by passing them to functions. The configuration in main.tf
only uses
a single EC2 instance. Update the configuration to use the
instances_per_subnet
variable to provision multiple EC2 instances per subnet.
Now when you apply this configuration, Terraform will provision
var.instances_per_subnet
instances for each private subnet configured in your
VPC workspace.
Configure region-specific AMIs
The AWS instance configuration also uses a hard-coded AMI ID, which is only
valid for the us-east-1
region. Use an aws_ami
data source to load the
correct AMI ID for the current region. Add the following to main.tf
.
Replace the hard-coded AMI ID with the one loaded from the new data source.
Configure EC2 subnet and security groups
Finally, update the EC2 instance configuration to use the subnet and security group configuration from the VPC workspace.
Apply the configuration and Terraform will provision the application
infrastructure. Respond to the confirmation prompt with a yes
.
After a few minutes, the load balancer health checks will pass, and will return the example response.
Tip
It can take several minutes for the load balancer to become available. If the curl command returns an error, try again after a few minutes.
Clean up your infrastructure
Before moving on, destroy the infrastructure you created in this tutorial.
In your learn-terraform-data-sources-app
directory, destroy the application
infrastructure. Respond to the confirmation prompt with yes
.
Note
You must destroy the application workspace before the VPC workspace. Since the resources in the application workspace depend on those in the VPC workspace, the AWS API will return an error if you attempt to destroy the VPC first.
Now change to the VPC directory.
Destroy this infrastructure as well. Once again, respond to the confirmation
prompt with yes
.
Note
Ensure that you use the same value for the aws_region
variable as you did
earlier in this tutorial.
If you used HCP Terraform for this tutorial, after destroying your resources,
delete the learn-terraform-data-sources-vpc
and
learn-terraform-data-sources-app
workspaces from your HCP Terraform
organization.
Next steps
In this tutorial, you used data sources to make your configuration more dynamic. You deployed two separate configurations for your application and network resources and used the terraform_remote_state data source to share data between them. You also replaced region-specific configuration with dynamic values from AWS provider data sources.
Now that you have used Terraform data sources, check out the following resources for more information.
- Read the Terraform Data Sources documentation.
- Connect HCP Terraform Workspaces with run triggers, and use outputs from one workspace to configure another workspace.
- Inject secrets into Terraform using the Vault provider.