State as a data source
Categories:
less than a minute
You can read data from state files and use it in your Terraform deployments. This is a very useful feature when building lots of different resources as it means you can automate a lot of data inputs.
This example demonstrates two resource types; an RDS MySQL database and a cluster of web servers in an autoscale group. Both are created by Terraform and they share an AWS S3 bucket to store state files.
The address and port number of the RDS instance is required by the instances running the web service. To avoid having to manually find and insert these values into code they can be retrieved dynamically from the Terraform state file by using a terraform_remote_state
block. This block can retireve the values from the state file by calling the data source
define the location of the RDS instance state file
data "terraform_remote_state" "db" {
backend = "s3"
config = {
bucket = "terraform-state-grinntec-learn-chapt03"
key = "stage/data-stores/mysql/terraform.tfstate"
region = "us-east-2"
}
}
specify the data required from the state file
db_address = data.terraform_remote_state.db.outputs.address
db_port = data.terraform_remote_state.db.outputs.port