---
title: Stacks
url: /docs/iac/concepts/stacks/
---


Every Pulumi program is deployed to a _stack_. A stack is an isolated, independently [configurable](/docs/iac/concepts/config/)
instance of a Pulumi program. Stacks are commonly used to denote different phases of development (such as `development`, `staging`, and `production`) or feature branches (such as `feature-x-dev`).

A project can have as many stacks as you need. By default, Pulumi creates a stack for you when you start a new project using the `pulumi new` command.

## Create a stack {#create-stack}

To create a new stack, use `pulumi stack init stackName`. This creates an empty stack `stackName` and sets it as the *active* stack. The project that the stack is associated with is determined by finding the nearest `Pulumi.yaml` file.

The stack name must be unique within a project. Stack names may only contain alphanumeric characters, hyphens, underscores, or periods.

```bash
$ pulumi stack init staging
```

The stack name is specified in one of the following formats:

1. `stackName`: Identifies the stack `stackName` in the current user account or default organization, and the project specified by the nearest `Pulumi.yaml` project file.
1. `orgName/stackName`: Identifies the stack `stackName` in the organization `orgName`, and the project specified by the nearest `Pulumi.yaml` project file.
1. `orgName/projectName/stackName`: Identifies the stack `stackName` in the organization `orgName` and the project `projectName`.  `projectName` must match the project specified by the nearest `Pulumi.yaml` project file.

> **Note:** For [DIY backend](/docs/iac/concepts/state-and-backends/#using-a-diy-backend), the `orgName` portion of the stack name must always be the constant value `organization`.

Additionally, backends initialized with a Pulumi CLI older than v3.61.0 support only the first format (`stackName`). You can upgrade these to support the other formats with the `pulumi state upgrade` command. See [State and Backends](/docs/iac/concepts/state-and-backends/) for more details.

Given the stack `my-org/my-project/dev`, the following are  all equivalent if the current organization is `my-org` and the current project is `my-project`:

```
my-org/my-project/dev
my-org/dev
dev
```

In some contexts, stack names will be presented in their fully qualified format (`orgName/projectName/stackName`) even if provided using shorthand (`stackName` or `orgName/stackName`) as input.

> **Note:** While stacks with applied configuration settings will often be accompanied by `Pulumi.<stack-name>.yaml` files, `pulumi stack init` creates one only when the stack's secrets provider stores its settings there, such as the passphrase provider's encryption salt or a cloud KMS provider's encrypted key. Otherwise, these files are created and managed with [`pulumi config`](/docs/iac/cli/commands/pulumi_config/). For information on how to populate your stack configuration files, see [Configuration](/docs/iac/concepts/config/).

## Listing stacks

To see the list of stacks associated with the current project (the nearest `Pulumi.yaml` file), use `pulumi stack ls`.

```bash
$ pulumi stack ls
NAME                                      LAST UPDATE              RESOURCE COUNT
jane-dev                                  4 hours ago              97
staging*                                  n/a                      n/a
broomellc/test                            2 weeks ago              121
```

Stack names in the listing will be partially qualified if they are associated with an organization or project different from the default for the context.

## Select a stack

The top-level `pulumi` operations `config`, `preview`, `update` and `destroy` operate on the *active* stack. To change the active stack, run `pulumi stack select`.

```bash
$ pulumi stack select jane-dev

$ pulumi stack ls
NAME                                      LAST UPDATE              RESOURCE COUNT
jane-dev*                                 4 hours ago              97
staging                                   n/a                      n/a
broomellc/test                            2 weeks ago              121
```

To select a stack that is part of an organization, use the fully qualified stack name, either `orgName/stackName` or `orgName/projectName/stackName`:

```bash
$ pulumi stack select mycompany/prod

$ pulumi stack ls
NAME                                      LAST UPDATE              RESOURCE COUNT
mycompany/prod*                            4 hours ago              97
mycompany/staging                          4 hours ago              97
dev                                       n/a                      n/a
```

## Rename a stack

To rename an existing stack, run `pulumi stack rename <new-name>`. The new name may be an unqualified stack name or a fully qualified name in the form `<org>/<project>/<stack>`:

```bash
$ pulumi stack rename production
$ pulumi stack rename myorg/myproject/production
```

Renaming a stack changes the value of the stack name returned to your program (for example, `pulumi.getStack()` in TypeScript/JavaScript or `pulumi.get_stack()` in Python). If that value is used to name any resources, the next `pulumi up` will attempt to replace those resources. Review the proposed changes carefully before proceeding, and consider whether a rename is the right operation or whether you should create a new stack instead.

### Cross-project renames

When the new stack name includes a different project name (for example, renaming from `myorg/old-project/prod` to `myorg/new-project/prod`), two additional manual steps are required after running `pulumi stack rename`.

1. **Update the project name in `Pulumi.yaml`.** The `name` field in `Pulumi.yaml` must match the project component of the fully qualified stack name. Edit the file to reflect the new project name before running `pulumi up`:

```yaml
    name: new-project  # was: old-project
    runtime: nodejs
    ```

1. **Update project-namespaced configuration keys.** Pulumi [configuration keys](/docs/iac/concepts/config/) are scoped by project name. Keys set without an explicit namespace are stored with the project name as the prefix, so a key named `database` in a project called `old-project` is recorded as `old-project:database` inside `Pulumi.<stack>.yaml`. After a cross-project rename, those keys still carry the old project prefix and will not be visible to the program running under the new project name.

> **Warning:** If you do not update project-namespaced configuration keys after a cross-project rename, the program will silently see those configuration values as unset and may fail at runtime or use unexpected defaults.

To update the keys, open `Pulumi.<stack>.yaml` in a text editor and rename each key that begins with the old project name:

```yaml
# Before
config:
  old-project:database: mydb
  old-project:region: us-west-2
  aws:region: us-west-2

# After
config:
  new-project:database: mydb
  new-project:region: us-west-2
  aws:region: us-west-2
```

Keys that include an explicit namespace other than the project name (such as `aws:region`) are unaffected and do not need to change. You can instead recreate each value using `pulumi config set` (or `pulumi config set --secret` for sensitive values) after updating `Pulumi.yaml`.

## Generate an update plan

> **Warning:** This is an **experimental feature**. Experimental features are opt-in (enabled with a flag, command, or environment variable), may change or be removed at any time, and are not necessarily supported. See What does "experimental" mean? (/docs/support/faq/infrastructure/#what-does-experimental-mean) for details. [Update plans](/docs/iac/operations/stack-management/update-plans/) only show up in `--help` when the environment variable `PULUMI_EXPERIMENTAL` is set to `true`.

To preview an update of the currently selected stack and save that plan run `pulumi preview --save-plan=plan.json`. The operation uses the latest [configuration values](/docs/iac/concepts/config/) for the active stack.

> **Note:** Your program code can distinguish between execution for `preview` and `update` operations by using [pulumi.runtime.isDryRun()](/docs/reference/pkg/nodejs/pulumi/pulumi/functions/runtime.isDryRun.html).

## Update a stack

To update the currently selected stack, run `pulumi up`. If you saved a plan from a preview you can pass that in to constrain the update to only doing what was planned with `pulumi up --plan=plan.json`. The operation uses the latest [configuration values](/docs/iac/concepts/config/) for the active stack.

## View stack resources

To view details of the currently selected stack, run `pulumi stack` with no arguments. This displays the metadata, resources and output properties associated with the stack.

```bash
$ pulumi stack
Current stack is acmecorp/dev:
    Owner: acmecorp
    Version: 4
    Active update: 0e9cb36d-3f4f-4c3a-9a8b-5d1c6c8b2f31
    Tags:
        pulumi:project           webserver
        pulumi:runtime           nodejs
        pulumi:secrets_provider  service
    Last updated: 1 week ago (2026-10-21 10:26:09.850357 -0700 PDT)
    Pulumi version used: v3.272.0
    Secrets provider: service
Current stack resources (4):
    TYPE                                    NAME
    pulumi:pulumi:Stack                     webserver-dev
    ├─ aws:ec2/securityGroup:SecurityGroup  web-secgrp
    ├─ aws:ec2/instance:Instance            web-server-www
    └─ pulumi:providers:aws                 default_7_52_1

Current stack outputs (2):
    OUTPUT     VALUE
    publicDns  ec2-203-0-113-12.us-west-2.compute.amazonaws.com
    publicIp   203.0.113.12

More information at: https://app.pulumi.com/acmecorp/webserver/dev

Use `pulumi stack select` to change stack; `pulumi stack ls` lists known ones
```

## Stack tags

> This [Pulumi Cloud](/docs/iac/concepts/pulumi-cloud/) feature is available in [all editions](/pricing/).

Stacks have associated metadata in the form of tags, with each tag consisting of a name and value. A set of built-in tags are automatically assigned and updated each time a stack is updated (such as `pulumi:project`, `pulumi:runtime`, `pulumi:description`, `gitHub:owner`, `gitHub:repo`, `vcs:owner`, `vcs:repo`, and `vcs:kind`). To view a stack's tags, run [`pulumi stack tag ls`](/docs/iac/cli/commands/pulumi_stack_tag_list/).

Custom tags can be assigned to a stack by running [`pulumi stack tag set <name> <value>`](/docs/iac/cli/commands/pulumi_stack_tag_set/) and can be used to customize the grouping of stacks in [Pulumi Cloud](https://app.pulumi.com/signin). For example, if you have many projects with separate stacks for production, staging, and testing environments, it may be useful to group stacks by environment instead of by project. To do this, you could assign a custom tag named `environment` to each stack. For example, running `pulumi stack tag set environment production` assigns a custom `environment` tag with a value of `production` to the active stack. Once you've assigned an `environment` tag to each stack, you'll be able to group by `Tag: environment` in Pulumi Cloud.

As a best practice, custom tags should not be prefixed with `pulumi:`, `gitHub:`, or `vcs:` to avoid conflicting with built-in tags that are assigned and updated with fresh values each time a stack is updated.

Tags can be deleted by running [`pulumi stack tag rm <name>`](/docs/iac/cli/commands/pulumi_stack_tag_remove/). Custom tags can also be created, edited, and deleted from each stack's **Overview** tab in the [Pulumi Cloud console](https://app.pulumi.com/signin).

## Stack outputs {#outputs}

A stack can export values as stack outputs. These outputs are shown during an update, can be easily retrieved with the Pulumi CLI, and are displayed in Pulumi Cloud. They can be used for important values like resource IDs, computed IP addresses, and DNS names.

To export values from a stack, use the following definition in the top-level of the entrypoint for your project:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
export const url = resource.url;

```

<!-- /option -->

<!-- option: python -->
```python
pulumi.export("url", resource.url)

```

<!-- /option -->

<!-- option: go -->
```go
ctx.Export("url", resource.Url)

```

<!-- /option -->

<!-- option: csharp -->
```csharp
public class MyStack : Stack
{
    public MyStack()
    {
        ...
        this.Url = resource.Url;
    }

    // 'url' is the output name. By default, it would take the property name 'Url'.
    [Output("url")] public Output<string> Url { get; set; }
}

```

<!-- /option -->

<!-- option: java -->
```java
public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        ctx.export("url", resource.url());
    }
}

```

<!-- /option -->

<!-- option: yaml -->
```yaml
outputs:
  url: ${resource.url}

```

<!-- /option -->

<!-- option: hcl -->
```hcl
output "url" {
  value = aws_instance.web.public_dns
}

```

<!-- /option -->

<!-- /chooser -->

From the CLI, you can then use [`pulumi stack output url`](/docs/iac/cli/commands/pulumi_stack_output/) to get the value and incorporate into other scripts or tools.

The value of a stack export can be a regular value, an [Output](/docs/iac/concepts/inputs-outputs/), or a `Promise` (effectively, the same as an [Input](/docs/iac/concepts/inputs-outputs/)). The actual values are resolved after `pulumi up` completes.

Stack exports are effectively JSON serialized, though quotes are removed when exporting strings.

For example, the following statements:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
export const x = "hello";
export const o = {num: 42};

```

<!-- /option -->

<!-- option: python -->
```python
pulumi.export("x", "hello")
pulumi.export("o", {'num': 42})

```

<!-- /option -->

<!-- option: go -->
```go
ctx.Export("x", pulumi.String("hello"))
ctx.Export("o", pulumi.Map(map[string]pulumi.Input{
    "num": pulumi.Int(42),
}))

```

<!-- /option -->

<!-- option: csharp -->
```csharp
class MyStack : Stack
{
    [Output] public Output<string> x { get; set; }
    [Output] public Output<ImmutableDictionary<string, int>> o { get; set; }

    public MyStack()
    {
        this.x = Output.Create("hello");
        this.o = Output.Create(
            new Dictionary<string, int> { { "num", 42 } }
                .ToImmutableDictionary());
    }
}

```

<!-- /option -->

<!-- option: java -->
```java
public static void stack(Context ctx) {
    ctx.export("x", Output.of("hello"));
    ctx.export("o", Output.of(Map.of(
            "num", "42"
    )));
}

```

<!-- /option -->

<!-- option: yaml -->
```yaml
outputs:
  x: hello
  o:
    num: 42

```

<!-- /option -->

<!-- option: hcl -->
```hcl
output "x" {
  value = "hello"
}

output "o" {
  value = { num = 42 }
}

```

<!-- /option -->

<!-- /chooser -->

produce the following stack outputs:

```bash
$ pulumi stack output x
hello
$ pulumi stack output o
{"num": 42}
```

The full set of outputs can be rendered as JSON by using `pulumi stack output --json`:

```bash
$ pulumi stack output --json
{
  "x": "hello",
  "o": {
      "num": 42
  }
}
```

> **Note:** If you export an actual resource, it too is JSON serialized. This usually isn’t what you want, especially because some resources are large. If you only want to export the resource’s ID or name, export those properties directly.

Stack outputs respect secret annotations and are encrypted appropriately. If a stack contains any secret values, their plaintext values will not be shown by default. Instead, they will be displayed as secret in the CLI. Pass `--show-secrets` to `pulumi stack output` to see the plaintext value.

## Stack README

> This [Pulumi Cloud](/docs/iac/concepts/pulumi-cloud/) feature is available in [all editions](/pricing/).

[Pulumi Cloud](https://app.pulumi.com/signin) renders a per-stack README on each stack's **README** tab from a stack output named `readme`. The README can include links, embedded documentation, and templated values that reference the stack's other outputs.

To add a README to a stack, export a stack output named `readme` whose value is the rendered markdown — most commonly by reading from a template file checked into your project (for example, `Pulumi.README.md`):

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
import { readFileSync } from "fs";
// The stack output must be named "readme".
export const readme = readFileSync("./Pulumi.README.md").toString();

```

<!-- /option -->

<!-- option: python -->
```python
import pulumi
with open('./Pulumi.README.md') as f:
    pulumi.export('readme', f.read())

```

<!-- /option -->

<!-- option: go -->
```go
func main() {
  pulumi.Run(func(ctx *pulumi.Context) error {
    readmeBytes, err := os.ReadFile("./Pulumi.README.md")
    if err != nil {
      return fmt.Errorf("failed to read readme: %w", err)
    }
    ctx.Export("readme", pulumi.String(string(readmeBytes)))
    return nil
  })
}

```

<!-- /option -->

<!-- option: csharp -->
```csharp
using Pulumi;
class MyStack : Stack
{
    public MyStack()
    {
        this.Readme = Output.Create(System.IO.File.ReadAllText("./Pulumi.README.md"));
    }
    [Output]
    public Output<string> Readme { get; set; }
}

```

<!-- /option -->

<!-- option: java -->
```java
package stackreadme;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
public class App {
    public static void main(String[] args) {
        Pulumi.run(ctx -> {
            try {
                var readme = Files.readString(Paths.get("./Pulumi.README.md"));
                ctx.export("readme", Output.of(readme));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}

```

<!-- /option -->

<!-- /chooser -->

The template file can reference other stack outputs (or resource properties) with `${...}` placeholders that Pulumi Cloud resolves when rendering. For example:

```markdown
# Pulumi Cloud README

[Sign in to AWS to view stack resources!](https://top-secret-url.com)

## On Call Operations

### Monitor

1. [Cloudwatch Metrics](https://us-west-2.console.aws.amazon.com/cloudwatch/home?region=us-west-2#dashboards:name=${outputs.dashboardName}): Monitor holistic metrics tracking overall service health
1. [RDS Performance Metrics](https://us-west-2.console.aws.amazon.com/rds/home?region=us-west-2#performance-insights-v20206:/resourceId/${database.databaseCluster.id}/resourceName/${outputs.rdsClusterWriterInstance}): Monitor RDS performance (wait times, top queries)
1. [Cloudwatch Logs](https://us-west-2.console.aws.amazon.com/cloudwatch/home?region=us-west-2#logStream:group=${outputs.cloudwatchLogGroup}): Search across service logs
```

After running `pulumi up`, the rendered README appears on the stack's **README** tab in the Pulumi Cloud console.

## Getting the current stack programmatically

The <!-- chooser: language -->
<!-- option: javascript -->
[`getStack`](/docs/reference/pkg/nodejs/pulumi/pulumi#getStack)
<!-- /option -->
<!-- option: typescript -->
[`getStack`](/docs/reference/pkg/nodejs/pulumi/pulumi#getStack)
<!-- /option -->
<!-- option: python -->
[`get_stack`](/docs/reference/pkg/python/pulumi/#pulumi.get_stack)
<!-- /option -->
<!-- option: go -->
[`context.Stack`](https://godoc.org/github.com/pulumi/pulumi/sdk/v3/go/pulumi#Context.Stack)
<!-- /option -->
<!-- option: csharp -->
`Deployment.StackName`
<!-- /option -->
<!-- /chooser -->
 function gives you the currently deploying stack, which can be useful in naming, tagging, or accessing resources.

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
let stack = pulumi.getStack();

```

<!-- /option -->

<!-- option: python -->
```python
stack = pulumi.get_stack()

```

<!-- /option -->

<!-- option: go -->
```go
stack := ctx.Stack()

```

<!-- /option -->

<!-- option: csharp -->
```csharp
var stack = Deployment.Instance.StackName;

```

<!-- /option -->

<!-- option: java -->
```java
var stack = ctx.stackName();

```

<!-- /option -->

<!-- option: yaml -->
```yaml
variables:
  stack: ${pulumi.stack}

```

<!-- /option -->

<!-- option: hcl -->
```hcl
locals {
  stack = pulumi.stack
}

```

The companion references `pulumi.project` and `pulumi.organization` are available the same way.

<!-- /option -->

<!-- /chooser -->

## Stack references {#stackreferences}

Stack references allow you to access the outputs of one stack from another stack, creating an inter-stack dependency between them.

To reference values from another stack, create an instance of the `StackReference` type using the fully qualified name of the stack as an input, and then read exported stack outputs by their name:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
import * as pulumi from "@pulumi/pulumi";
const other = new pulumi.StackReference("acmecorp/infra/other");
const otherOutput = other.getOutput("x");

```

<!-- /option -->

<!-- option: python -->
```python
from pulumi import StackReference

other = StackReference(f"acmecorp/infra/other")
other_output = other.get_output("x");

```

<!-- /option -->

<!-- option: go -->
```go
other, err := pulumi.NewStackReference(ctx, "acmecorp/infra/other", nil)
if err != nil {
    return err
}
otherOutput := other.GetOutput(pulumi.String("x"))

```

<!-- /option -->

<!-- option: csharp -->
```csharp
var other = new StackReference("acmecorp/infra/other");
var otherOutput = other.GetOutput("x");

```

<!-- /option -->

<!-- option: java -->
```java
var other = new StackReference("acmecorp/infra/other");
var otherOutput = other.output("x");

```

<!-- /option -->

<!-- option: yaml -->
```yaml
resources:
  my-stack-reference:
    type: pulumi:pulumi:StackReference
    properties:
      name: acmecorp/infra/other

variables:
  stack_output: ${my-stack-reference.outputs["x"]}

```

<!-- /option -->

<!-- option: hcl -->
In Pulumi HCL, a stack reference is a `pulumi_stack_reference` resource. Its `outputs` attribute is a map of the referenced stack’s exports, indexed by name:
```hcl
resource "pulumi_stack_reference" "other" {
  name = "acmecorp/infra/other"
}

locals {
  other_output = pulumi_stack_reference.other.outputs["x"]
}

```

<!-- /option -->

<!-- /chooser -->

Use the fully qualified stack name, including the organization, project, and stack name components, in the format `<organization>/<project>/<stack>`.

For example, suppose you need to define a cluster's infrastructure in one project and consume it from another.
One project, `infra`, defines a Kubernetes cluster and another, `services`, deploys
services into it. If you do this across three distinct environments — production, staging,
and testing — you have six distinct stacks that pair up in the following ways:

* `mycompany/infra/production` provides the cluster used by `mycompany/services/production`
* `mycompany/infra/staging` provides the cluster used by `mycompany/services/staging`
* `mycompany/infra/testing` provides the cluster used by `mycompany/services/testing`

The way Pulumi programs communicate information for external consumption is by using stack exports. For example,
your infrastructure stack might export the Kubernetes configuration information needed to deploy into a cluster:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
export const kubeConfig = ... a cluster's output property ...;

```

<!-- /option -->

<!-- option: python -->
```python
pulumi.export("kubeConfig", ... a cluster's output property ...)

```

<!-- /option -->

<!-- option: go -->
```go
ctx.Export("kubeConfig", /*...a cluster's output property...*/)

```

<!-- /option -->

<!-- option: csharp -->
```csharp
class ClusterStack : Stack
{
    [Output] public Output<string> KubeConfig { get; set; }

    public ClusterStack()
    {
        // ... a cluster is created ...

        this.KubeConfig = ... a cluster's output property ...
    }
}

```

<!-- /option -->

<!-- option: java -->
```java
ctx.export("kubeConfig", /*...a cluster's output property...*/);

```

<!-- /option -->

<!-- option: yaml -->
```yaml
outputs:
  kubeConfig: ... # a cluster's output property

```

<!-- /option -->

<!-- option: hcl -->
```hcl
output "kubeConfig" {
  value = module.cluster.kubeconfig # a cluster's output property
}

```

<!-- /option -->

<!-- /chooser -->

The challenge in this scenario is that the services project needs to ingest this output during deployment so that it can
connect to the Kubernetes cluster provisioned in its respective environment.

The Pulumi programming model offers a way to do this with its `StackReference` resource type. For example:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
import * as k8s from "@pulumi/kubernetes";
import * as pulumi from "@pulumi/pulumi";
const env = pulumi.getStack();
const infra = new pulumi.StackReference(`mycompany/infra/${env}`);
const provider = new k8s.Provider("k8s", { kubeconfig: infra.getOutput("kubeConfig") });
const service = new k8s.core.v1.Service(..., { provider: provider });

```

<!-- /option -->

<!-- option: python -->
```python
from pulumi import get_stack, ResourceOptions, StackReference
from pulumi_kubernetes import Provider, core

env = get_stack()
infra = StackReference(f"mycompany/infra/{env}")
provider = Provider("k8s", kubeconfig=infra.get_output("kubeConfig"))
service = core.v1.Service(..., ResourceOptions(provider=provider))

```

<!-- /option -->

<!-- option: go -->
```go
import (
  "fmt"

  "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
  pulumi.Run(func(ctx *pulumi.Context) error {
    slug := fmt.Sprintf("mycompany/infra/%v", ctx.Stack())
    stackRef, err := pulumi.NewStackReference(ctx, slug, nil)
    if err != nil {
      return err
    }

    kubeConfig := stackRef.GetOutput(pulumi.String("kubeConfig"))
    // ...
    return nil
  })
}

```

<!-- /option -->

<!-- option: csharp -->
```csharp
using Pulumi;
using Pulumi.Kubernetes;
using Pulumi.Kubernetes.Core.V1;

class AppStack : Stack
{
    public AppStack()
    {
        var cluster = new StackReference($"mycompany/infra/{Deployment.Instance.StackName}");
        var kubeConfig = cluster.RequireOutput("KubeConfig").Apply(v => v.ToString());
        var provider = new Provider("k8s", new ProviderArgs { KubeConfig = kubeConfig });
        var options = new CustomResourceOptions { Provider = provider };
        var service = new Service(..., ..., options);
    }
}

```

<!-- /option -->

<!-- option: java -->
```java
package myproject;

import com.pulumi.Context;
import com.pulumi.Pulumi;

import com.pulumi.core.Output;
import com.pulumi.kubernetes.Provider;
import com.pulumi.kubernetes.ProviderArgs;
import com.pulumi.kubernetes.core.v1.Service;
import com.pulumi.kubernetes.core.v1.ServiceArgs;
import com.pulumi.resources.CustomResourceOptions;
import com.pulumi.resources.StackReference;

public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        var cluster = new StackReference(String.format("mycompany/infra/%s", ctx.stackName()));
        var kubeconfig = cluster.requireOutput(Output.of("kubeConfig")).applyValue(String::valueOf);
        var provider = new Provider("k8s", ProviderArgs.builder().kubeconfig(kubeconfig).build());
        var options = CustomResourceOptions.builder()
            .provider(provider)
            .build();
        var service = new Service("app-service", ServiceArgs.builder()
            ...
            .build(), options);
    }
}

```

<!-- /option -->

<!-- option: yaml -->
```yaml
variables:
  kubeConfig: ${my-stack-reference.outputs["kubeConfig"]}
resources:
  my-stack-reference:
    type: pulumi:pulumi:StackReference
    properties:
      name: mycompany/infra/${pulumi.stack}
  provider:
    type: pulumi:providers:kubernetes
    properties:
      kubeconfig: ${kubeConfig}
  service:
    type: some:resource:type
    properties: ...
    options:
      provider: ${provider}

```

<!-- /option -->

<!-- option: hcl -->
```hcl
terraform {
  required_providers {
    kubernetes = {
      source = "pulumi/kubernetes"
    }
  }
}

resource "pulumi_stack_reference" "infra" {
  name = "mycompany/infra/${pulumi.stack}"
}

provider "kubernetes" {
  kubeconfig = pulumi_stack_reference.infra.outputs["kubeConfig"]
}

resource "kubernetes_namespace" "app" {
  metadata = {
    name = "my-app"
  }
}

```

The `pulumi/` source prefix selects the native Pulumi Kubernetes provider, which takes a `kubeconfig` argument directly. The bridged `hashicorp/kubernetes` provider you would get from an unqualified `kubernetes` source configures itself differently — with `config_path`, `host`, and friends — so check the provider’s own documentation when you use a bridged provider here.

<!-- /option -->

<!-- /chooser -->

The `StackReference` constructor takes as input a string of the form `<organization>/<project>/<stack>`, and lets
you access the outputs of that stack.

In the above example, you construct a stack reference to a specific stack in this project which has the same name
as your current stack (i.e. when deploying the "staging" stack of the above program, you reference the "staging" stack)
from the infra project. Once you have that resource, you can read output variables from it.
From that point on, Pulumi understands the inter-stack dependency for scenarios like cascading updates.

### Reading outputs from stack references

Stack references support the following methods for reading outputs from the referenced stack:

* `requireOutput` returns an `Output` wrapping the named output value and fails at deployment
  time if the output does not exist in the referenced stack. This is the recommended method for
  most use cases, as it surfaces a missing or misspelled output name as a clear, immediate error
  rather than silently propagating an undefined value.
* `getOutput` returns an `Output` wrapping the named output value, or an `Output` wrapping
  `undefined` (or `None` in Python) if the output does not exist. Use this only when the
  absence of an output is an expected and explicitly handled condition in your program.
* `getOutputDetails` returns an `OutputDetails` object that provides direct access to the output
  value, bypassing the `Output` wrapper. This is most useful when you need the raw value for
  use in your program's logic, or when you need to distinguish between a non-secret output
  (available as `.value`) and a secret output (available as `.secretValue`).

The following example uses `requireOutput`, the recommended default that fails at deployment
time if the output is missing, to read a `vpcId` export:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
const infra: StackReference = new pulumi.StackReference("acmecorp/infra/prod");

// Fails at deployment time if "vpcId" is not in the referenced stack's exports.
const vpcId: Output<any> = infra.requireOutput("vpcId");

```

<!-- /option -->

<!-- option: python -->
```python
infra = StackReference("acmecorp/infra/prod")

# Fails at deployment time if "vpcId" is not in the referenced stack's exports.
vpc_id = infra.require_output("vpcId")

```

<!-- /option -->

<!-- option: go -->
```go
infra, err := pulumi.NewStackReference(ctx, "acmecorp/infra/prod", nil)
if err != nil {
    return err
}

// Fails at deployment time if "vpcId" is not in the referenced stack's exports.
vpcId := infra.GetStringOutput(pulumi.String("vpcId"))

```

<!-- /option -->

<!-- option: csharp -->
```csharp
var infra = new StackReference("acmecorp/infra/prod");

// Fails at deployment time if "vpcId" is not in the referenced stack's exports.
var vpcId = infra.RequireOutput("vpcId");

```

<!-- /option -->

<!-- option: java -->
```java
StackReference infra = new StackReference("acmecorp/infra/prod");

// Fails at deployment time if "vpcId" is not in the referenced stack's exports.
Output<?> vpcId = infra.requireOutput("vpcId");

```

<!-- /option -->

<!-- option: yaml -->
```yaml
resources:
  infra:
    type: pulumi:pulumi:StackReference
    properties:
      name: acmecorp/infra/prod

variables:
  # Fails at deployment time if "vpcId" is not in the referenced stack's exports.
  vpcId: ${infra.outputs["vpcId"]}

```

<!-- /option -->

<!-- option: hcl -->
```hcl
resource "pulumi_stack_reference" "infra" {
  name = "acmecorp/infra/prod"
}

locals {
  # Fails at deployment time if "vpcId" is not in the referenced stack's exports.
  vpc_id = pulumi_stack_reference.infra.outputs["vpcId"]
}

```

**Note:** Indexing the `outputs` map is the Pulumi HCL equivalent of `requireOutput`: a name that
the referenced stack does not export is an `Invalid index` error at deployment time. For
`getOutput` behavior, see the next example.

<!-- /option -->

<!-- /chooser -->

The following example uses `getOutput`, which lets a missing output propagate silently, to read
a `privateIp` output, then transforms it with `Output.apply` to build a derived value:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
const infra: StackReference = new pulumi.StackReference(...);
const ip: Output<any> = infra.getOutput("privateIp");
const logKey: Output<string> = ip.apply(ip => `logs/${ip}.log`);
const logFile: aws.s3.BucketObject = new aws.s3.BucketObject("log", {
    // ...
    key: logKey
});

```

<!-- /option -->

<!-- option: python -->
```python
infra = StackReference(...)
ip = infra.get_output("privateIp")
log_key = ip.apply(lambda ip: f"logs/{ip}.log")
log_file = aws.s3.BucketObject("log",
    # ...
    key=log_key,
)

```

<!-- /option -->

<!-- option: go -->
```go
infra, err := pulumi.NewStackReference(ctx, ...)
if err != nil {
    return err
}
ip := infra.GetOutput(pulumi.String("privateIp"))
logKey := ip.ApplyT(func(ip interface{}) string {
    return fmt.Sprintf("logs/%v.log", ip)
}).(pulumi.StringOutput)
logFile, err := s3.NewBucketObject(ctx, "log", &s3.BucketObjectArgs{
    // ...
    Key: logKey,
})

```

<!-- /option -->

<!-- option: csharp -->
```csharp
var infra = new StackReference(...);
var ip = infra.GetOutput("privateIp");
var logKey = ip.Apply(ip => $"logs/{ip}.log");
var logFile = new Aws.S3.BucketObject("log", new Aws.S3.BucketObjectArgs
{
    // ...
    Key = logKey,
});

```

<!-- /option -->

<!-- option: java -->
```java
StackReference infra = new StackReference(...);
Output<?> ip = infra.output("privateIp");
Output<String> logKey = ip.applyValue(value -> String.format("logs/%s.log", value));
BucketObject logFile = new BucketObject("log", new BucketObjectArgs.Builder()
    // ...
    .key(logKey)
    .build());

```

<!-- /option -->

<!-- option: yaml -->
```yaml
resources:
  infra:
    type: pulumi:pulumi:StackReference
    properties:
      name: acmecorp/infra/prod
  logFile:
    type: aws:s3:BucketObject
    properties:
      key: logs/${infra.outputs["privateIp"]}.log

```

**Note:** Pulumi YAML does not distinguish between `requireOutput` and `getOutput`. Accessing a stack
reference output via interpolation will fail at deployment time if the named output does not
exist in the referenced stack.

<!-- /option -->

<!-- option: hcl -->
Wrap the lookup in [`try`](/docs/iac/languages-sdks/hcl/hcl-language-reference/#try-and-can), or use `lookup` with a fallback, to get `getOutput`’s tolerance of a missing name. No `apply` step is needed: an ordinary HCL expression over a stack reference output produces a derived value directly.
```hcl
resource "pulumi_stack_reference" "infra" {
  name = "acmecorp/infra/prod"
}

locals {
  ip      = try(pulumi_stack_reference.infra.outputs["privateIp"], "unknown")
  log_key = "logs/${local.ip}.log"
}

resource "aws_s3_object" "log" {
  # ...
  key = local.log_key
}

```

<!-- /option -->

<!-- /chooser -->

The following example uses `getOutputDetails`, which bypasses the `Output` wrapper, in a case
where the referenced stack exports a database hostname as a plain string:

<!-- chooser: language -->

<!-- option: typescript -->
```typescript
const infra = new pulumi.StackReference("acmecorp/infra/prod");
const dbHostDetails = await infra.getOutputDetails("dbHost");

// For non-secret outputs, the value is in .value.
// For outputs marked as secret in the referenced stack, use .secretValue instead.
const dbHost = dbHostDetails.value as string;

```

Note that your Pulumi program must export a top-level `async` function
to be able to use the `await` operator.
```javascript
export = async () => {
    // ...
}

```

See [JavaScript program entrypoint](/docs/iac/languages-sdks/javascript/#program-entrypoint)
for more information.

<!-- /option -->

<!-- option: python -->
Because `get_output_details` is awaited, your Pulumi program must register an async
entrypoint with `pulumi.run`. This requires version 3.254.0 or later of the Pulumi
Python SDK.
```python
import pulumi
from pulumi import StackReference

async def main():
    infra = StackReference("acmecorp/infra/prod")
    db_host_details = await infra.get_output_details("dbHost")

    # For non-secret outputs, the value is in .value.
    # For outputs marked as secret in the referenced stack, use .secret_value instead.
    db_host = db_host_details.value

pulumi.run(main)

```

See [async entrypoint](/docs/iac/languages-sdks/python/#async-entrypoint)
for more information.

<!-- /option -->

<!-- option: go -->
```go
infra, err := pulumi.NewStackReference(ctx, "acmecorp/infra/prod", nil)
if err != nil {
    return err
}
dbHostDetails, err := infra.GetOutputDetails("dbHost")
if err != nil {
    return err
}

// For non-secret outputs, the value is in .Value.
// For outputs marked as secret in the referenced stack, use .SecretValue instead.
dbHost := dbHostDetails.Value.(string)

```

<!-- /option -->

<!-- option: csharp -->
```csharp
var infra = new StackReference("acmecorp/infra/prod");
var dbHostDetails = await infra.GetOutputDetailsAsync("dbHost");

// For non-secret outputs, the value is in .Value.
// For outputs marked as secret in the referenced stack, use .SecretValue instead.
var dbHost = (string)dbHostDetails.Value;

```

Note that your Pulumi program must be inside an `async` function
to be able to use the `await` operator.
```csharp
return await Deployment.RunAsync(async () =>
{
    // ...
});

```

<!-- /option -->

<!-- option: java -->
```java
StackReference infra = new StackReference("acmecorp/infra/prod");
infra.outputDetailsAsync("dbHost").thenAccept(dbHostDetails -> {
    // For non-secret outputs, the value is in getValue().
    // For outputs marked as secret in the referenced stack, use getSecretValue() instead.
    String dbHost = (String) dbHostDetails.getValue().get();
    // ...
});

```

<!-- /option -->

<!-- option: yaml -->

**Note:** `getOutputDetails` is not supported in Pulumi YAML. To read a stack reference
output in YAML, use the `outputs` property of a `StackReference` resource, as shown in the
`requireOutput` example above.

<!-- /option -->

<!-- option: hcl -->

**Note:** `getOutputDetails` has no Pulumi HCL equivalent. HCL expressions are not wrapped in
`Output`, so there is nothing to unwrap: index the `outputs` map of a
`pulumi_stack_reference` resource, as shown in the `requireOutput` example above, and use
the result like any other value. A secret output stays secret as it flows through the
program.

<!-- /option -->

<!-- /chooser -->

## Import and export a stack deployment

A stack can be exported to see the raw data associated with the stack. This is useful when manual changes need to be applied to the stack due to changes made in the target cloud platform that Pulumi is not aware of. The modified stack can then be imported to set the current state of the stack to the new values.

> **Warning:** This is a powerful capability that subverts the usual way that Pulumi manages resources and ensures immutable and repeatable infrastructure deployments. Importing an incorrect stack specification could lead to the orphaning of cloud resources or the inability to make future updates to the stack. Use care when using the import and export capabilities.

```bash
$ pulumi stack export --file stack.json

$ pulumi stack import --file stack.json
```

## Destroy a stack

Before deleting a stack, if the stack still has resources associated with it, they must first be deleted via `pulumi destroy`. This command uses the latest configuration values, rather than the ones that were last used when the program was deployed.

> **Note:** There are scenarios when `pulumi destroy` may fail to delete resources as expected due to dependencies, permissions, or the resources being in a locked or protected state. For detailed steps on how to troubleshoot and resolve these issues, refer to our [troubleshooting guide](/docs/iac/operations/troubleshooting/).

## Delete a stack

To delete a stack with no resources, run `pulumi stack rm`. Removing the stack removes all stack history from Pulumi Cloud and deletes the stack configuration file `Pulumi.<stack-name>.yaml`.

To force the deletion of a stack that still contains resources---potentially orphaning them---use `pulumi stack rm --force`.

> **Note:** If a stack is deleted by mistake, organization administrators can restore it from the Pulumi Cloud console for a limited time. See [Restoring deleted stacks](/docs/iac/operations/stack-management/restoring-deleted-stacks/).


