Data Sources
Terraform data sources fetch information from external APIs and from other Terraform configurations. For example, you may want to import disk image IDs from a cloud provider or share data between configurations for different parts of your infrastructure.
When to Use Data Sources
Use data sources when you need to reference dynamic data that is not known until after Terraform applies a configuration. For example, instance IDs that cloud providers assign on creation.
When data is static or you know the values before synthesizing your code, we recommend creating static references in your preferred programming language or using Terraform variables.
Define Data Sources
Data Sources are part of a Terraform provider. All classes representing Data Sources are prefixed with Data
.
In the following TypeScript example, a Terraform data source fetches the AWS region DataAwsRegion
from the AWS provider.
import { TerraformStack } from "cdktf";
import { Construct } from "constructs";
import { AwsProvider } from "@cdktf/provider-aws/lib/aws-provider";
import { DataAwsRegion } from "@cdktf/provider-aws/lib/data-aws-region";
export class DataSourcesStack extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
new AwsProvider(this, "aws", {
region: "us-west-2",
});
const region = new DataAwsRegion(this, "region");
}
}
Remote State Data Source
The terraform_remote_state
data source retrieves state data from a remote Terraform backend. This allows you to use the root-level outputs of one or more Terraform configurations as input data for another configuration. For example, a core infrastructure team can handle building the core machines, networking, etc. and then expose some information to other teams that allows them to run their own infrastructure. Refer to the Remote Backends page for more details.
The following example uses the global DataTerraformRemoteState
to reference a Terraform Output of another Terraform configuration.
import { TerraformStack } from "cdktf";
import { Construct } from "constructs";
import { AwsProvider } from "@cdktf/provider-aws/lib/aws-provider";
import { DataTerraformRemoteState } from "cdktf";
import { Instance } from "@cdktf/provider-aws/lib/instance";
export class DataSourcesStack extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
new AwsProvider(this, "aws", {
region: "us-west-2",
});
const remoteState = new DataTerraformRemoteState(this, "remote-state", {
organization: "hashicorp",
workspaces: {
name: "vpc-prod",
},
});
new Instance(this, "foo", {
instanceType: "t2.micro",
ami: "ami-123456",
subnetId: `${remoteState.get("subnet_id")}`,
});
}
}