• HashiCorp Developer

  • HashiCorp Cloud Platform
  • Terraform
  • Packer
  • Consul
  • Vault
  • Boundary
  • Nomad
  • Waypoint
  • Vagrant
Terraform
  • Install
  • Tutorials
    • About the Docs
    • Configuration Language
    • Terraform CLI
    • Terraform Cloud
    • Terraform Enterprise
    • CDK for Terraform
    • Provider Use
    • Plugin Development
    • Registry Publishing
    • Integration Program
  • Registry(opens in new tab)
  • Try Cloud(opens in new tab)
  • Sign up
Terraform Home

CDK for Terraform

Skip to main content
  • CDK for Terraform
  • Get Started
    • Architecture
    • HCL Interoperability
    • Constructs
    • Providers
    • Resources
    • Modules
    • Data Sources
    • Variables and Outputs
    • Functions
    • Iterators
    • Remote Backends
    • Aspects
    • Assets
    • Tokens
    • Stacks
  • Community
  • Telemetry

  • Resources

  • Tutorial Library
  • Certifications
  • Community Forum
    (opens in new tab)
  • Support
    (opens in new tab)
  • GitHub
    (opens in new tab)
  • Terraform Registry
    (opens in new tab)
  1. Developer
  2. Terraform
  3. CDK for Terraform
  4. Concepts
  5. Data Sources
  • CDK For Terraform
  • v0.14.x
  • v0.13.x
  • v0.12.x
  • v0.11.x
  • v0.10.x
  • v0.9.x
  • v0.8.x

»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");
  }
}
import imports.aws.data_aws_region.DataAwsRegion;
import imports.aws.provider.AwsProvider;
import imports.aws.provider.AwsProviderConfig;

public class DataSourcesDefine extends TerraformStack {

    public DataSourcesDefine(Construct scope, String id){
        super(scope, id);

        new AwsProvider(this, "temp", AwsProviderConfig.builder()
                .region("us-east-1")
                .build()
        );
        //......
        DataAwsRegion region = new DataAwsRegion(this, "region");
    }
}
from cdktf import TerraformStack, App
from imports.aws.data_aws_region import DataAwsRegion
from imports.aws.provider import AwsProvider

class HelloTerraform(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        AwsProvider(self, "aws",
                    region="us-east-1"
                    )

        # .....
        region = DataAwsRegion(self, "region")


app = App()
HelloTerraform(app, "data-sources")
app.synth()
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Constructs;
using HashiCorp.Cdktf;
using aws.Provider;
using aws.DataAwsRegion;

namespace Examples
{
    class DataSourceStack : TerraformStack
    {
        public DataSourceStack(Construct scope, string name) : base(scope, name)
        {

            new AwsProvider(this, "aws", new AwsProviderConfig {
                Region = "eu-central-1"
            });

            DataAwsRegion region = new DataAwsRegion(this, "region", new DataAwsRegionConfig {
                Name = "eu-central-1"
            });
        }
    }
}

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")}`,
    });
  }
}
import com.hashicorp.cdktf.DataTerraformRemoteState;
import com.hashicorp.cdktf.DataTerraformRemoteStateRemoteConfig;
import imports.aws.instance.Instance;
import imports.aws.instance.InstanceConfig;

public class DataSourcesRemoteState extends TerraformStack {

    public DataSourcesRemoteState(Construct scope, String id) {
        super(scope, id);

        // ....
        DataTerraformRemoteState remoteState = new DataTerraformRemoteState(this, "state",
                DataTerraformRemoteStateRemoteConfig.builder()
                        .organization("hashicorp")
                        .workspaces(new NamedRemoteWorkspace("vpc-prod"))
                        .build());

        new Instance(this, "foo", InstanceConfig.builder()
                // ....
                .subnetId(remoteState.getString("subnet_id"))
                .build());
    }
}
from cdktf import TerraformStack, App
from cdktf import DataTerraformRemoteState, NamedRemoteWorkspace
class HelloTerraformRemoteState(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        AwsProvider(self, "aws",
            region="us-east-1"
        )

        # .....
        remoteState = DataTerraformRemoteState(self, "vpc-prod-remote-state",
                            organization="hashicorp",
                            workspaces=NamedRemoteWorkspace(name='vpc-prod')
                        )

        Instance(self, "foo",
            # .....
            subnet_id=remoteState.get_string('subnet_id')
        )
app = App()
HelloTerraformRemoteState(app, "terraform-remotes-state")
app.synth()
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Constructs;
using HashiCorp.Cdktf;
using aws.Provider;
using aws.Instance;

namespace Examples
{
    class RemoteStateDataSourceStack : TerraformStack
    {
        public RemoteStateDataSourceStack(Construct scope, string name) : base(scope, name)
        {

            new AwsProvider(this, "aws", new AwsProviderConfig {
                Region = "eu-central-1"
            });

            DataTerraformRemoteState remoteState = new DataTerraformRemoteState(this, "remoteState", new DataTerraformRemoteStateRemoteConfig {
                Organization = "hashicorp",
                Workspaces = new NamedRemoteWorkspace("vpc-prod")
            });

            new Instance(this, "foo", new InstanceConfig {
                // ....
                SubnetId = remoteState.GetString("subnet_id")
            });
        }
    }
}
Edit this page on GitHub

On this page

  1. Data Sources
  2. When to Use Data Sources
  3. Define Data Sources
  4. Remote State Data Source
Give Feedback(opens in new tab)
  • Certifications
  • System Status
  • Terms of Use
  • Security
  • Privacy
  • Trademark Policy
  • Trade Controls
  • Give Feedback(opens in new tab)