Skip to content

Reference Terraform state ​

Why reference state? ​

Rather than migrating your entire Terraform infrastructure to Pulumi, you can reference existing Terraform state files to access outputs and resource attributes. This enables coexistence where different teams can use their preferred tools while sharing infrastructure.

Common scenarios include:

  • Operations teams manage core infrastructure with Terraform
  • Development teams deploy applications with Pulumi
  • Gradual adoption of Pulumi happens alongside existing Terraform workflows

Reference existing infrastructure state ​

Here's an example of a minimal Terraform config that centrally manages an AWS ECS cluster and ECR repository. Pulumi can reference these outputs programmatically.

hcl
# An AWS ECS Cluster
resource "aws_ecs_cluster" "cluster" {
  name = "app-cluster"
}

# An AWS ECR Repository
resource "aws_ecr_repository" "repo" {
  name = "image-repo"
}

# Outputs that Pulumi will reference
output "ecs_cluster_name" {
  value = aws_ecs_cluster.cluster.name
}

output "ecr_repository_url" {
  value = aws_ecr_repository.repo.repository_url
}

Reference local state files ​

For Terraform workspaces using local state files, you can reference them directly, via the getLocalReference function:

typescript
import * as terraform from "@pulumi/terraform";

// Reference local Terraform state
const tfState = terraform.state.getLocalReferenceOutput({
    path: "../infrastructure/terraform.tfstate",
});

// Access Terraform outputs
const ecsClusterName = tfState.outputs["ecs_cluster_name"];
const ecrRepository = tfState.outputs["ecr_repository_url"];

Reference remote state ​

For production environments, many prefer to store their state in Terraform Cloud. To reference remote state, use the getRemoteReference function:

typescript
import * as terraform from "@pulumi/terraform";

// Reference remote Terraform state
const tfState = terraform.state.getRemoteReferenceOutput({
    token: "<secret-token>",
    organization: "my-org",
    workspaces: {
        prefix: "dev",
    },
});

// Access Terraform outputs
const ecsClusterName = tfState.outputs["ecs_cluster_name"];
const ecrRepository = tfState.outputs["ecr_repository_url"];

Example: Containerized application on ECS ​

Let's create a practical example where an internal platform engineering team uses Terraform to manage an ECS cluster and ECR repository, while the developer teams use Pulumi to manage containerized application deployments via Fargate.

Terraform infrastructure (reference) ​

The Terraform configuration for your company-wide ECS/ECR platform might look like this:

hcl
# infrastructure/main.tf
resource "aws_ecs_cluster" "cluster" {
  name = "app-cluster"
}

resource "aws_ecr_repository" "repo" {
  name = "app-container-repo"
}

# Outputs that Pulumi will reference
output "ecs_cluster_arn" {
  value = aws_ecs_cluster.cluster.arn
}

output "ecr_repository_url" {
  value = aws_ecr_repository.repo.repository_url
}

Pulumi application deployment ​

As a developer using this platform, we want to make a small containerized web app and deploy it.

First, we need to make the app. It will consist of a directory called app/ holding a small index.html file, and a Dockerfile that defines an Nginx web server to host it.

Example: app/index.html - The HTML page

html
<html>
  <head><meta charset="UTF-8">
    <title>Hello Fargate</title>
  </head>
  <body>
      <p>I LOVE PULUMI!</p>
      <p>Made with ❤️ with <a href="https://pulumi.com">Pulumi</a></p>
  </body>
</html>

Example: app/Dockerfile - The Nginx proxy

FROM nginx
COPY index.html /usr/share/nginx/html

Next, we'll make a TypeScript Pulumi program that packages this up into a Docker image and runs the app on the company's shared infrastructure.

Example: index.ts - A Pulumi program that references the shared infrastructure

typescript
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
import * as pulumi from "@pulumi/pulumi";
import * as terraform from "@pulumi/terraform";

// Reference local Terraform state
const tfState = terraform.state.getLocalReferenceOutput({
    path: "../infrastructure/terraform.tfstate",
});

// Access Terraform outputs
const clusterArn = tfState.outputs["ecs_cluster_arn"];
const repoUrl = tfState.outputs["ecr_repository_url"];

// Build and publish our application's container image from ./app to the ECR repository.
const image = new awsx.ecr.Image("image", {
    repositoryUrl: repoUrl,
    context: "./app",
    platform: "linux/amd64",
});

// Create a load balancer to listen for requests and route them to the container.
const loadbalancer = new awsx.lb.ApplicationLoadBalancer("loadbalancer", {});

// Define the service and configure it to use our image and load balancer.
const service = new awsx.ecs.FargateService("service", {
    cluster: clusterArn,
    assignPublicIp: true,
    taskDefinitionArgs: {
        container: {
            name: "awsx-ecs",
            image: image.imageUri,
            cpu: 128,
            memory: 512,
            essential: true,
            portMappings: [{
                containerPort: 80,
                targetGroup: loadbalancer.defaultTargetGroup,
            }],
        },
    },
});

// Export the URL so we can easily access it.
export const frontendURL = pulumi.interpolate `http://${loadbalancer.loadBalancer.dnsName}`;

Before deploying, apply the Terraform configuration so that the state file the Pulumi program reads actually exists. From the infrastructure/ directory:

bash
terraform init
terraform apply

That writes infrastructure/terraform.tfstate, which the Pulumi program references at ../infrastructure/terraform.tfstate.

With the program in place, initialize a Pulumi project and stack for it with pulumi new if you haven't already, then deploy it with pulumi up:

bash
pulumi up

Our Pulumi program references a local Terraform state file to get the important details (the ECS ARN, the ECR URL), packages up the application into a Docker image, pushes that image to the ECR repo, creates a load balancer, and then defines a Fargate service that uses all of the above to run the containerized app. Finally, we see the deployed URL as a Pulumi output, and can immediately see that the app is running and serving up the HTML file.

This example demonstrates how Pulumi can seamlessly consume Terraform outputs to deploy applications on existing shared infrastructure.

Reference multiple state files ​

Larger Terraform estates usually split state by layer, such as networking in one workspace and security in another. A Pulumi program can read from as many state files as it needs. This example uses getS3Reference, the counterpart of getLocalReference and getRemoteReference for state stored in an S3 bucket, to combine outputs from two workspaces:

typescript
import * as aws from "@pulumi/aws";
import * as terraform from "@pulumi/terraform";

const networkState = terraform.state.getS3ReferenceOutput({
    bucket: "terraform-state",
    key: "network/terraform.tfstate",
});

const securityState = terraform.state.getS3ReferenceOutput({
    bucket: "terraform-state",
    key: "security/terraform.tfstate",
});

const cluster = new aws.ecs.Cluster("app-cluster", {
    configuration: {
        executeCommandConfiguration: {
            kmsKeyId: securityState.outputs["kms_key_id"],
            logging: "DEFAULT",
        },
    },
});

export const privateSubnetIds = networkState.outputs["private_subnet_ids"];

Each call returns an object whose outputs map holds the values the Terraform configuration exports through its output blocks. Those values are Pulumi outputs, so pass them directly into other resources rather than treating them as plain strings.

Best practices ​

  1. Use consistent naming: Ensure Terraform output names are descriptive and stable
  2. Secure state access: Use Terraform Cloud to control access to state files
  3. Document dependencies: Document which Pulumi stacks depend on which Terraform states
  4. Monitor state changes: Be aware that changes to Terraform outputs will affect dependent Pulumi stacks

Content from the official Pulumi documentation (github.com/pulumi/docs).