auto

package
v3.113.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 53 Imported by: 91

README

Automation API

Programmatic infrastructure.

Godocs

See the full godocs for the most extensive and up to date information including full examples coverage:

https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/auto?tab=doc

Examples

Multiple full working examples with detailed walkthroughs can be found in this repo:

https://github.com/pulumi/automation-api-examples

Overview

Package auto contains the Pulumi Automation API, the programmatic interface for driving Pulumi programs without the CLI. Generally this can be thought of as encapsulating the functionality of the CLI (pulumi up, pulumi preview, pulumi destroy, pulumi stack init, etc.) but with more flexibility. This still requires a CLI binary to be installed and available on your $PATH.

In addition to fine-grained building blocks, Automation API provides three out of the box ways to work with Stacks:

  1. Programs locally available on-disk and addressed via a filepath (NewStackLocalSource)
    stack, err := NewStackLocalSource(ctx, "myOrg/myProj/myStack", filepath.Join("..", "path", "to", "project"))
  1. Programs fetched from a Git URL (NewStackRemoteSource)
	stack, err := NewStackRemoteSource(ctx, "myOrg/myProj/myStack", GitRepo{
		URL:         "https:github.com/pulumi/test-repo.git",
		ProjectPath: filepath.Join("project", "path", "repo", "root", "relative"),
    })
  1. Programs defined as a function alongside your Automation API code (NewStackInlineSource)
	 stack, err := NewStackInlineSource(ctx, "myOrg/myProj/myStack", "myProj", func(pCtx *pulumi.Context) error {
		bucket, err := s3.NewBucket(pCtx, "bucket", nil)
		if err != nil {
			return err
		}
		pCtx.Export("bucketName", bucket.Bucket)
		return nil
     })

Each of these creates a stack with access to the full range of Pulumi lifecycle methods (up/preview/refresh/destroy), as well as methods for managing config, stack, and project settings.

	 err := stack.SetConfig(ctx, "key", ConfigValue{ Value: "value", Secret: true })
	 preRes, err := stack.Preview(ctx)
	 detailed info about results
     fmt.Println(preRes.prev.Steps[0].URN)

The Automation API provides a natural way to orchestrate multiple stacks, feeding the output of one stack as an input to the next as shown in the package-level example below. The package can be used for a number of use cases:

  • Driving pulumi deployments within CI/CD workflows
  • Integration testing
  • Multi-stage deployments such as blue-green deployment patterns
  • Deployments involving application code like database migrations
  • Building higher level tools, custom CLIs over pulumi, etc
  • Using pulumi behind a REST or GRPC API
  • Debugging Pulumi programs (by using a single main entrypoint with "inline" programs)

To enable a broad range of runtime customization the API defines a Workspace interface. A Workspace is the execution context containing a single Pulumi project, a program, and multiple stacks. Workspaces are used to manage the execution environment, providing various utilities such as plugin installation, environment configuration ($PULUMI_HOME), and creation, deletion, and listing of Stacks. Every Stack including those in the above examples are backed by a Workspace which can be accessed via:

	 w = stack.Workspace()
     err := w.InstallPlugin("aws", "v3.2.0")

Workspaces can be explicitly created and customized beyond the three Stack creation helpers noted above:

	 w, err := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "project", "path"), PulumiHome("~/.pulumi"))
     s := NewStack(ctx, "org/proj/stack", w)

A default implementation of workspace is provided as LocalWorkspace. This implementation relies on Pulumi.yaml and Pulumi..yaml as the intermediate format for Project and Stack settings. Modifying ProjectSettings will alter the Workspace Pulumi.yaml file, and setting config on a Stack will modify the Pulumi..yaml file. This is identical to the behavior of Pulumi CLI driven workspaces. Custom Workspace implementations can be used to store Project and Stack settings as well as Config in a different format, such as an in-memory data structure, a shared persistent SQL database, or cloud object storage. Regardless of the backing Workspace implementation, the Pulumi SaaS Console will still be able to display configuration applied to updates as it does with the local version of the Workspace today.

The Automation API also provides error handling utilities to detect common cases such as concurrent update conflicts:

	uRes, err :=stack.Up(ctx)
	if err != nil && IsConcurrentUpdateError(err) { /* retry logic here */ }

Developing the Godocs

This repo has extensive examples and godoc content. To test out your changes locally you can do the following:

  1. enlist in the appropriate pulumi branch:
  2. cd $GOPATH/src/github.com/pulumi/pulumi/sdk/go/auto
  3. godoc -http=:6060
  4. Navigate to http://localhost:6060/pkg/github.com/pulumi/pulumi/sdk/v3/go/auto/

Known Issues

Please upvote issues, add comments, and open new ones to help prioritize our efforts: https://github.com/pulumi/pulumi/issues?q=is%3Aissue+is%3Aopen+label%3Aarea%2Fautomation-api

Documentation

Overview

Package auto contains the Pulumi Automation API, the programmatic interface for driving Pulumi programs without the CLI. Generally this can be thought of as encapsulating the functionality of the CLI (`pulumi up`, `pulumi preview`, pulumi destroy`, `pulumi stack init`, etc.) but with more flexibility. This still requires a CLI binary to be installed and available on your $PATH.

In addition to fine-grained building blocks, Automation API provides three out of the box ways to work with Stacks:

  1. Programs locally available on-disk and addressed via a filepath (NewStackLocalSource) stack, err := NewStackLocalSource(ctx, "myOrg/myProj/myStack", filepath.Join("..", "path", "to", "project"))

  2. Programs fetched from a Git URL (NewStackRemoteSource) stack, err := NewStackRemoteSource(ctx, "myOrg/myProj/myStack", GitRepo{ URL: "https://github.com/pulumi/test-repo.git", ProjectPath: filepath.Join("project", "path", "repo", "root", "relative"), })

  3. Programs defined as a function alongside your Automation API code (NewStackInlineSource) stack, err := NewStackInlineSource(ctx, "myOrg/myProj/myStack", func(pCtx *pulumi.Context) error { bucket, err := s3.NewBucket(pCtx, "bucket", nil) if err != nil { return err } pCtx.Export("bucketName", bucket.Bucket) return nil })

Each of these creates a stack with access to the full range of Pulumi lifecycle methods (up/preview/refresh/destroy), as well as methods for managing config, stack, and project settings.

err := stack.SetConfig(ctx, "key", ConfigValue{ Value: "value", Secret: true })
preRes, err := stack.Preview(ctx)
// detailed info about results
fmt.Println(preRes.prev.Steps[0].URN)

The Automation API provides a natural way to orchestrate multiple stacks, feeding the output of one stack as an input to the next as shown in the package-level example below. The package can be used for a number of use cases:

  • Driving pulumi deployments within CI/CD workflows

  • Integration testing

  • Multi-stage deployments such as blue-green deployment patterns

  • Deployments involving application code like database migrations

  • Building higher level tools, custom CLIs over pulumi, etc

  • Using pulumi behind a REST or GRPC API

  • Debugging Pulumi programs (by using a single main entrypoint with "inline" programs)

To enable a broad range of runtime customization the API defines a `Workspace` interface. A Workspace is the execution context containing a single Pulumi project, a program, and multiple stacks. Workspaces are used to manage the execution environment, providing various utilities such as plugin installation, environment configuration ($PULUMI_HOME), and creation, deletion, and listing of Stacks. Every Stack including those in the above examples are backed by a Workspace which can be accessed via:

w = stack.Workspace()
err := w.InstallPlugin("aws", "v3.2.0")

Workspaces can be explicitly created and customized beyond the three Stack creation helpers noted above:

w, err := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "project", "path"), PulumiHome("~/.pulumi"))
s := NewStack(ctx, "org/proj/stack", w)

A default implementation of workspace is provided as `LocalWorkspace`. This implementation relies on Pulumi.yaml and Pulumi.<stack>.yaml as the intermediate format for Project and Stack settings. Modifying ProjectSettings will alter the Workspace Pulumi.yaml file, and setting config on a Stack will modify the Pulumi.<stack>.yaml file. This is identical to the behavior of Pulumi CLI driven workspaces. Custom Workspace implementations can be used to store Project and Stack settings as well as Config in a different format, such as an in-memory data structure, a shared persistent SQL database, or cloud object storage. Regardless of the backing Workspace implementation, the Pulumi SaaS Console will still be able to display configuration applied to updates as it does with the local version of the Workspace today.

The Automation API also provides error handling utilities to detect common cases such as concurrent update conflicts:

uRes, err :=stack.Up(ctx)
if err != nil && IsConcurrentUpdateError(err) { /* retry logic here */ }
Example
ctx := context.Background()

// This stack creates an output
projA := "projA"
stackName := FullyQualifiedStackName("myOrg", projA, "devStack")
stackA, err := NewStackInlineSource(ctx, stackName, projA, func(pCtx *pulumi.Context) error {
	pCtx.Export("outputA", pulumi.String("valueA"))
	return nil
})
if err != nil {
	// return errors.Wrap(err, "failed to create stackA")
}
// deploy the stack
aRes, err := stackA.Up(ctx)
if err != nil {
	// return errors.Wrap(err, "failed to update bucket stackA")
}

// this stack creates an uses stackA's output to create a new output
projB := "projB"
stackName = FullyQualifiedStackName("myOrg", projB, "devStack")
stackB, err := NewStackInlineSource(ctx, stackName, projB, func(pCtx *pulumi.Context) error {
	// output a new value "valueA/valueB"
	pCtx.Export(
		"outputB",
		pulumi.Sprintf(
			"%s/%s",
			pulumi.String(aRes.Outputs["outputA"].Value.(string)), pulumi.String("valueB"),
		),
	)
	return nil
})
if err != nil {
	// return errors.Wrap(err, "failed to create object stackB")
}
// deploy the stack
bRes, err := stackB.Up(ctx)
if err != nil {
	// return errors.Wrap(err, "failed to update stackB")
}

// Success!
fmt.Println(bRes.Summary.Result)
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrParsePermalinkFailed = errors.New("failed to get permalink")

ErrParsePermalinkFailed occurs when the the generated permalink URL can't be found in the op result

Functions

func FullyQualifiedStackName

func FullyQualifiedStackName(org, project, stack string) string

FullyQualifiedStackName returns a stack name formatted with the greatest possible specificity: org/project/stack or user/project/stack Using this format avoids ambiguity in stack identity guards creating or selecting the wrong stack. Note that legacy diy backends (local file, S3, Azure Blob) do not support stack names in this format, and instead only use the stack name without an org/user or project to qualify it. See: https://github.com/pulumi/pulumi/issues/2522. Non-legacy diy backends do support the org/project/stack format but org must be set to "organization".

Example
stackName := FullyQualifiedStackName("myOrgName", "myProjectName", "myStackName")
// "myOrgName/myProjectName/myStackName"
ctx := context.Background()
_, _ = NewStackLocalSource(ctx, stackName, filepath.Join(".", "project"))
Output:

func GetPermalink(stdout string) (string, error)

GetPermalink returns the permalink URL in the Pulumi Console for the update or refresh operation. This will error for alternate, diy backends.

func IsCompilationError

func IsCompilationError(e error) bool

IsCompilationError returns true if the program failed at the build/run step (only Typescript, Go, .NET)

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "broken", "go", "program"))
_, err := s.Up(ctx)
if err != nil && IsCompilationError(err) {
	// time to fix up the program
}
Output:

func IsConcurrentUpdateError

func IsConcurrentUpdateError(e error) bool

IsConcurrentUpdateError returns true if the error was a result of a conflicting update locking the stack.

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "update", "inprogress", "program"))
_, err := s.Up(ctx)
if err != nil && IsConcurrentUpdateError(err) {
	// stack "o/p/s" already has an update in progress
	// implement some retry logic here...
}
Output:

func IsCreateStack409Error

func IsCreateStack409Error(e error) bool

IsCreateStack409Error returns true if the error was a result of creating a stack that already exists.

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "stack", "alreadyexists", "program"))
_, err := s.Up(ctx)
if err != nil && IsCreateStack409Error(err) {
	// stack "o/p/s" already exists
	// implement some retry logic here...
}
Output:

func IsRuntimeError

func IsRuntimeError(e error) bool

IsRuntimeError returns true if there was an error in the user program at during execution.

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "runtime", "error", "program"))
_, err := s.Up(ctx)
if err != nil && IsRuntimeError(err) {
	// oops, maybe there's an NPE in the program?
}
Output:

func IsSelectStack404Error

func IsSelectStack404Error(e error) bool

IsSelectStack404Error returns true if the error was a result of selecting a stack that does not exist.

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "stack", "notfound", "program"))
_, err := s.Up(ctx)
if err != nil && IsSelectStack404Error(err) {
	// stack "o/p/s" does not exist
	// implement some retry logic here...
}
Output:

func IsUnexpectedEngineError

func IsUnexpectedEngineError(e error) bool

IsUnexpectedEngineError returns true if the pulumi core engine encountered an error (most likely a bug).

Example
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "engine", "error", "program"))
_, err := s.Up(ctx)
if err != nil && IsUnexpectedEngineError(err) {
	// oops, you've probably uncovered a bug in the pulumi engine.
	// please file a bug report :)
}
Output:

Types

type ChangeSecretsProviderOptions added in v3.97.0

type ChangeSecretsProviderOptions struct {
	// NewPassphrase is the new passphrase when changing to a `passphrase` provider
	NewPassphrase *string
}

type ConfigMap

type ConfigMap map[string]ConfigValue

ConfigMap is a map of ConfigValue used by Pulumi programs. Allows differentiating between secret and plaintext values.

Example
cfg := ConfigMap{
	"plaintext": {Value: "unencrypted"},
	"secret":    {Value: "encrypted", Secret: true},
}
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "project"))
s.SetAllConfig(ctx, cfg)
Output:

type ConfigOptions added in v3.60.1

type ConfigOptions struct {
	Path bool
}

ConfigOptions is a configuration option used by a Pulumi program. Allows to use the path flag while getting/setting the configuration.

type ConfigValue

type ConfigValue struct {
	Value  string
	Secret bool
}

ConfigValue is a configuration value used by a Pulumi program. Allows differentiating between secret and plaintext values by setting the `Secret` property.

Example
cfgVal := ConfigValue{
	Value:  "an secret that will be marked as and stored encrypted",
	Secret: true,
}
ctx := context.Background()
s, _ := NewStackLocalSource(ctx, "o/p/s", filepath.Join(".", "project"))
s.SetConfig(ctx, "cfgKey", cfgVal)
Output:

type DestroyResult

type DestroyResult struct {
	StdOut  string
	StdErr  string
	Summary UpdateSummary
}

DestroyResult is the output of a successful Stack.Destroy operation

Example
ctx := context.Background()
// select an existing stack
s, _ := SelectStackLocalSource(ctx, "o/p/s", filepath.Join(".", "project"))
destroyRes, _ := s.Destroy(ctx)
// success!
fmt.Println(destroyRes.Summary.Result)
Output:

func (dr *DestroyResult) GetPermalink() (string, error)

GetPermalink returns the permalink URL in the Pulumi Console for the destroy operation.

type DockerImageCredentials added in v3.111.0

type DockerImageCredentials struct {
	Username string
	Password string
}

type EnvVarValue added in v3.45.0

type EnvVarValue struct {
	Value  string
	Secret bool
}

EnvVarValue represents the value of an envvar. A value can be a secret, which is passed along to remote operations when used with remote workspaces, otherwise, it has no affect.

type ExecutorImage added in v3.111.0

type ExecutorImage struct {
	Image       string
	Credentials *DockerImageCredentials
}

type GitAuth

type GitAuth struct {
	// The absolute path to a private key for access to the git repo
	// When using `SSHPrivateKeyPath`, the URL of the repository must be in the format
	// git@github.com:org/repository.git - if the url is not in this format, then an error
	// `unable to clone repo: invalid auth method` will be returned
	SSHPrivateKeyPath string
	// The (contents) private key for access to the git repo.
	// When using `SSHPrivateKey`, the URL of the repository must be in the format
	// git@github.com:org/repository.git - if the url is not in this format, then an error
	// `unable to clone repo: invalid auth method` will be returned
	SSHPrivateKey string
	// The password that pairs with a username or as part of an SSH Private Key
	Password string
	// PersonalAccessToken is a Git personal access token in replacement of your password
	PersonalAccessToken string
	// Username is the username to use when authenticating to a git repository
	Username string
}

GitAuth is the authentication details that can be specified for a private Git repo. There are 3 different authentication paths: * PersonalAccessToken * SSHPrivateKeyPath (and it's potential password) * Username and Password Only 1 authentication path is valid. If more than 1 is specified it will result in an error

type GitRepo

type GitRepo struct {
	// URL to clone git repo
	URL string
	// Optional path relative to the repo root specifying location of the pulumi program.
	// Specifying this option will update the Workspace's WorkDir accordingly.
	ProjectPath string
	// Optional branch to checkout.
	Branch string
	// Optional commit to checkout.
	CommitHash string
	// Optional function to execute after enlisting in the specified repo.
	Setup SetupFn
	// GitAuth is the different Authentication options for the Git repository
	Auth *GitAuth
	// Shallow disables fetching the repo's entire history.
	Shallow bool
}

GitRepo contains info to acquire and setup a Pulumi program from a git repository.

Example
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

// we'll compile a the program into an executable with the name "examplesBinary"
binName := "examplesBinary"
repo := GitRepo{
	URL:         "https://github.com/pulumi/test-repo.git",
	ProjectPath: "goproj",
	// this call back will get executed post-clone to allow for additional program setup
	Setup: func(ctx context.Context, workspace Workspace) error {
		cmd := exec.Command("go", "build", "-o", binName, "main.go")
		cmd.Dir = workspace.WorkDir()
		return cmd.Run()
	},
}
// an override to the project file in the git repo, specifying our pre-built executable
project := workspace.Project{
	Name: tokens.PackageName(pName),
	Runtime: workspace.NewProjectRuntimeInfo("go", map[string]interface{}{
		"binary": binName,
	}),
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo, Project(project))
Output:

Example (PersonalAccessToken)
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

// Get the Sourcecode Repository PERSONAL_ACCESS_TOKEN
token, _ := os.LookupEnv("PERSONAL_ACCESS_TOKEN")

repo := GitRepo{
	URL:         "https://github.com/pulumi/test-repo.git",
	ProjectPath: "goproj",
	Auth: &GitAuth{
		PersonalAccessToken: token,
	},
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo)
Output:

Example (PrivateKey)
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

repo := GitRepo{
	URL:         "git@github.com:pulumi/test-repo.git",
	ProjectPath: "goproj",
	Auth: &GitAuth{
		SSHPrivateKey: "<PRIVATE KEY FILE CONTENTS HERE>",
		Password:      "PrivateKeyPassword",
	},
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo)
Output:

Example (PrivateKeyPath)
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

repo := GitRepo{
	URL:         "git@github.com:pulumi/test-repo.git",
	ProjectPath: "goproj",
	Auth: &GitAuth{
		SSHPrivateKeyPath: "/Users/myuser/.ssh/id_rsa",
		Password:          "PrivateKeyPassword",
	},
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo)
Output:

Example (UsernameAndPassword)
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

repo := GitRepo{
	URL:         "https://github.com/pulumi/test-repo.git",
	ProjectPath: "goproj",
	Auth: &GitAuth{
		// This will use a username and password combination for the private repo
		Username: "myuser",
		Password: "myPassword1234!",
	},
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo)
Output:

type LocalWorkspace

type LocalWorkspace struct {
	// contains filtered or unexported fields
}

LocalWorkspace is a default implementation of the Workspace interface. A Workspace is the execution context containing a single Pulumi project, a program, and multiple stacks. Workspaces are used to manage the execution environment, providing various utilities such as plugin installation, environment configuration ($PULUMI_HOME), and creation, deletion, and listing of Stacks. LocalWorkspace relies on Pulumi.yaml and Pulumi.<stack>.yaml as the intermediate format for Project and Stack settings. Modifying ProjectSettings will alter the Workspace Pulumi.yaml file, and setting config on a Stack will modify the Pulumi.<stack>.yaml file. This is identical to the behavior of Pulumi CLI driven workspaces.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// install the pulumi-aws plugin
w.InstallPlugin(ctx, "aws", "v3.2.0")
// fetch the config used with the last update on stack "org/proj/stack"
w.RefreshConfig(ctx, "org/proj/stack")
Output:

Example (SecretsProvider)
ctx := context.Background()
// WorkDir sets the working directory for the LocalWorkspace. The workspace will look for a default
// project settings file (Pulumi.yaml) in this location for information about the Pulumi program.
wd := WorkDir(filepath.Join("..", "path", "to", "pulumi", "project"))
// PulumiHome customizes the location of $PULUMI_HOME where metadata is stored and plugins are installed.
ph := PulumiHome(filepath.Join("~", ".pulumi"))
// Project provides ProjectSettings to set once the workspace is created.
proj := Project(workspace.Project{
	Name:    tokens.PackageName("myproject"),
	Runtime: workspace.NewProjectRuntimeInfo("go", nil),
	Backend: &workspace.ProjectBackend{
		URL: "https://url.to.custom.saas.backend.com",
	},
})
// Secrets provider provides a way of passing a non-default secrets provider to the
// workspace and the stacks created from it. Supported secrets providers are:
// `awskms`, `azurekeyvault`, `gcpkms`, `hashivault` and `passphrase`
secretsProvider := SecretsProvider("awskms://alias/mysecretkeyalias")
// EnvVars is a map of environment values scoped to the workspace.
// These values will be passed to all Workspace and Stack level commands.
envvars := EnvVars(map[string]string{
	"PULUMI_CONFIG_PASSPHRASE": "password",
})
_, _ = NewLocalWorkspace(ctx, wd, ph, proj, secretsProvider, envvars)
Output:

func (*LocalWorkspace) AddEnvironments added in v3.97.0

func (l *LocalWorkspace) AddEnvironments(ctx context.Context, stackName string, envs ...string) error

AddEnvironments adds environments to the end of a stack's import list. Imported environments are merged in order per the ESC merge rules. The list of environments behaves as if it were the import list in an anonymous environment.

func (*LocalWorkspace) ChangeStackSecretsProvider added in v3.97.0

func (l *LocalWorkspace) ChangeStackSecretsProvider(
	ctx context.Context, stackName, newSecretsProvider string, opts *ChangeSecretsProviderOptions,
) error

ChangeStackSecretsProvider edits the secrets provider for the given stack.

func (*LocalWorkspace) CreateStack

func (l *LocalWorkspace) CreateStack(ctx context.Context, stackName string) error

CreateStack creates and sets a new stack with the stack name, failing if one already exists.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// initialize the stack
err := w.CreateStack(ctx, "org/proj/stack")
if err != nil {
	// failed to create the stack
}
Output:

func (*LocalWorkspace) ExportStack

func (l *LocalWorkspace) ExportStack(ctx context.Context, stackName string) (apitype.UntypedDeployment, error)

ExportStack exports the deployment state of the stack matching the given name. This can be combined with ImportStack to edit a stack's state (such as recovery from failed deployments).

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "existing_stack")
dep, _ := w.ExportStack(ctx, stackName)
// import/export is backwards compatible, and we must write code specific to the version we're dealing with.
if dep.Version != 3 {
	panic("expected deployment version 3")
}
var state apitype.DeploymentV3
_ = json.Unmarshal(dep.Deployment, &state)

// ... perform edits on the state ...

// marshal out updated deployment state
bytes, _ := json.Marshal(state)
dep.Deployment = bytes
// import our edited deployment state back to our stack
_ = w.ImportStack(ctx, stackName, dep)
Output:

func (*LocalWorkspace) GetAllConfig

func (l *LocalWorkspace) GetAllConfig(ctx context.Context, stackName string) (ConfigMap, error)

GetAllConfig returns the config map for the specified stack name, scoped to the current workspace. LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// get all config from the workspace for the stack (read from Pulumi.stack.yaml)
cfg, _ := w.GetAllConfig(ctx, "org/proj/stack")
fmt.Println(cfg["config_key"].Value)
fmt.Println(cfg["config_key"].Secret)
Output:

func (*LocalWorkspace) GetConfig

func (l *LocalWorkspace) GetConfig(ctx context.Context, stackName string, key string) (ConfigValue, error)

GetConfig returns the value associated with the specified stack name and key, scoped to the current workspace. LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// get all config from the workspace for the stack (read from Pulumi.stack.yaml)
cfgVal, _ := w.GetConfig(ctx, "org/proj/stack", "config_key")
fmt.Println(cfgVal.Value)
fmt.Println(cfgVal.Secret)
Output:

func (*LocalWorkspace) GetConfigWithOptions added in v3.60.1

func (l *LocalWorkspace) GetConfigWithOptions(
	ctx context.Context, stackName string, key string, opts *ConfigOptions,
) (ConfigValue, error)

GetConfigWithOptions returns the value associated with the specified stack name and key, using the optional ConfigOptions, scoped to the current workspace. LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.

func (*LocalWorkspace) GetEnvVars

func (l *LocalWorkspace) GetEnvVars() map[string]string

GetEnvVars returns the environment values scoped to the current workspace.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// get all environment values from the workspace for the stack
e := w.GetEnvVars()
for k, v := range e {
	fmt.Println(k)
	fmt.Println(v)
}
Output:

func (*LocalWorkspace) GetTag added in v3.57.0

func (l *LocalWorkspace) GetTag(ctx context.Context, stackName string, key string) (string, error)

GetTag returns the value associated with the specified stack name and key.

func (*LocalWorkspace) ImportStack

func (l *LocalWorkspace) ImportStack(ctx context.Context, stackName string, state apitype.UntypedDeployment) error

ImportStack imports the specified deployment state into a pre-existing stack. This can be combined with ExportStack to edit a stack's state (such as recovery from failed deployments).

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "existing_stack")
dep, _ := w.ExportStack(ctx, stackName)
// import/export is backwards compatible, and we must write code specific to the version we're dealing with.
if dep.Version != 3 {
	panic("expected deployment version 3")
}
var state apitype.DeploymentV3
_ = json.Unmarshal(dep.Deployment, &state)

// ... perform edits on the state ...

// marshal out updated deployment state
bytes, _ := json.Marshal(state)
dep.Deployment = bytes
// import our edited deployment state back to our stack
_ = w.ImportStack(ctx, stackName, dep)
Output:

func (*LocalWorkspace) InstallPlugin

func (l *LocalWorkspace) InstallPlugin(ctx context.Context, name string, version string) error

InstallPlugin acquires the plugin matching the specified name and version.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
w.InstallPlugin(ctx, "aws", "v3.2.0")
Output:

func (*LocalWorkspace) InstallPluginFromServer added in v3.44.0

func (l *LocalWorkspace) InstallPluginFromServer(
	ctx context.Context,
	name string,
	version string,
	server string,
) error

InstallPluginFromServer acquires the plugin matching the specified name and version from a third party server.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
w.InstallPluginFromServer(ctx, "scaleway", "v1.2.0", "github://api.github.com/lbrlabs")
Output:

func (*LocalWorkspace) ListEnvironments added in v3.100.0

func (l *LocalWorkspace) ListEnvironments(ctx context.Context, stackName string) ([]string, error)

ListEnvironments returns the list of environments from the provided stack's configuration.

func (*LocalWorkspace) ListPlugins

func (l *LocalWorkspace) ListPlugins(ctx context.Context) ([]workspace.PluginInfo, error)

ListPlugins lists all installed plugins.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
ps, _ := w.ListPlugins(ctx)
fmt.Println(ps[0].Size)
Output:

func (*LocalWorkspace) ListStacks

func (l *LocalWorkspace) ListStacks(ctx context.Context) ([]StackSummary, error)

ListStacks returns all Stacks created under the current Project. This queries underlying backend and may return stacks not present in the Workspace (as Pulumi.<stack>.yaml files).

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
ss, _ := w.ListStacks(ctx)
fmt.Println(ss[0].UpdateInProgress)
Output:

func (*LocalWorkspace) ListTags added in v3.57.0

func (l *LocalWorkspace) ListTags(ctx context.Context, stackName string) (map[string]string, error)

ListTags Returns the tag map for the specified stack name.

func (*LocalWorkspace) PostCommandCallback

func (l *LocalWorkspace) PostCommandCallback(ctx context.Context, stackName string) error

PostCommandCallback is a hook executed after every command. Called with the stack name. An extensibility point to perform workspace cleanup (CLI operations may create/modify a Pulumi.stack.yaml) LocalWorkspace does not utilize this extensibility point.

func (*LocalWorkspace) Program

func (l *LocalWorkspace) Program() pulumi.RunFunc

Program returns the program `pulumi.RunFunc` to be used for Preview/Update if any. If none is specified, the stack will refer to ProjectSettings for this information.

func (*LocalWorkspace) ProjectSettings

func (l *LocalWorkspace) ProjectSettings(ctx context.Context) (*workspace.Project, error)

ProjectSettings returns the settings object for the current project if any LocalWorkspace reads settings from the Pulumi.yaml in the workspace. A workspace can contain only a single project at a time.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// read existing project settings if any
ps, err := w.ProjectSettings(ctx)
if err != nil {
	// no Pulumi.yaml was found, so create a default
	ps = &workspace.Project{
		Name:    tokens.PackageName("myproject"),
		Runtime: workspace.NewProjectRuntimeInfo("go", nil),
	}
}
// make some changes
author := "pulumipus"
ps.Author = &author
// save the settings back to the Workspace
w.SaveProjectSettings(ctx, ps)
Output:

func (*LocalWorkspace) PulumiCommand added in v3.104.0

func (l *LocalWorkspace) PulumiCommand() PulumiCommand

PulumiCommand returns the PulumiCommand instance that is used to execute commands.

func (*LocalWorkspace) PulumiHome

func (l *LocalWorkspace) PulumiHome() string

PulumiHome returns the directory override for CLI metadata if set. This customizes the location of $PULUMI_HOME where metadata is stored and plugins are installed.

func (*LocalWorkspace) PulumiVersion

func (l *LocalWorkspace) PulumiVersion() string

PulumiVersion returns the version of the underlying Pulumi CLI/Engine.

func (*LocalWorkspace) RefreshConfig

func (l *LocalWorkspace) RefreshConfig(ctx context.Context, stackName string) (ConfigMap, error)

RefreshConfig gets and sets the config map used with the last Update for Stack matching stack name. It will overwrite all configuration in the Pulumi.<stack>.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackNameA := FullyQualifiedStackName("org", "proj", "stackA")
// get the last deployed config from stack A
// this overwrites config in pulumi.stackA.yaml
cfg, _ := w.RefreshConfig(ctx, stackNameA)
// add a key to the ConfigMap
cfg["addition_config_key"] = ConfigValue{Value: "additional_config_value"}
// create a new stack
stackNameB := FullyQualifiedStackName("org", "proj", "stackB")
w.CreateStack(ctx, stackNameB)
// save the modified config to stackB
w.SetAllConfig(ctx, stackNameB, cfg)
Output:

func (*LocalWorkspace) RemoveAllConfig

func (l *LocalWorkspace) RemoveAllConfig(ctx context.Context, stackName string, keys []string) error

RemoveAllConfig removes all values in the provided key list for the specified stack name It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "stackA")
// get all config currently set in the workspace
cfg, _ := w.GetAllConfig(ctx, stackName)
keys := slice.Prealloc[string](len(cfg))
for k := range cfg {
	keys = append(keys, k)
}
// remove those config values
_ = w.RemoveAllConfig(ctx, stackName, keys)
Output:

func (*LocalWorkspace) RemoveAllConfigWithOptions added in v3.60.1

func (l *LocalWorkspace) RemoveAllConfigWithOptions(
	ctx context.Context, stackName string, keys []string, opts *ConfigOptions,
) error

RemoveAllConfigWithOptions removes all values in the provided key list for the specified stack name using the optional ConfigOptions It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().

func (*LocalWorkspace) RemoveConfig

func (l *LocalWorkspace) RemoveConfig(ctx context.Context, stackName string, key string) error

RemoveConfig removes the specified key-value pair on the provided stack name. It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "stackA")
_ = w.RemoveConfig(ctx, stackName, "key_to_remove")
Output:

func (*LocalWorkspace) RemoveConfigWithOptions added in v3.60.1

func (l *LocalWorkspace) RemoveConfigWithOptions(
	ctx context.Context, stackName string, key string, opts *ConfigOptions,
) error

RemoveConfigWithOptions removes the specified key-value pair on the provided stack name. It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().

func (*LocalWorkspace) RemoveEnvironment added in v3.97.0

func (l *LocalWorkspace) RemoveEnvironment(ctx context.Context, stackName string, env string) error

RemoveEnvironment removes an environment from a stack's configuration.

func (*LocalWorkspace) RemovePlugin

func (l *LocalWorkspace) RemovePlugin(ctx context.Context, name string, version string) error

RemovePlugin deletes the plugin matching the specified name and verision.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
_ = w.RemovePlugin(ctx, "aws", "v3.2.0")
Output:

func (*LocalWorkspace) RemoveStack

func (l *LocalWorkspace) RemoveStack(ctx context.Context, stackName string, opts ...optremove.Option) error

RemoveStack deletes the stack and all associated configuration and history.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "stack")
_ = w.RemoveStack(ctx, stackName)
Output:

func (*LocalWorkspace) RemoveTag added in v3.57.0

func (l *LocalWorkspace) RemoveTag(ctx context.Context, stackName string, key string) error

RemoveTag removes the specified key-value pair on the provided stack name.

func (*LocalWorkspace) SaveProjectSettings

func (l *LocalWorkspace) SaveProjectSettings(ctx context.Context, settings *workspace.Project) error

SaveProjectSettings overwrites the settings object in the current project. There can only be a single project per workspace. Fails is new project name does not match old. LocalWorkspace writes this value to a Pulumi.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// read existing project settings if any
ps, err := w.ProjectSettings(ctx)
if err != nil {
	// no Pulumi.yaml was found, so create a default
	ps = &workspace.Project{
		Name:    tokens.PackageName("myproject"),
		Runtime: workspace.NewProjectRuntimeInfo("go", nil),
	}
}
// make some changes
author := "pulumipus"
ps.Author = &author
// save the settings back to the Workspace
w.SaveProjectSettings(ctx, ps)
Output:

func (*LocalWorkspace) SaveStackSettings

func (l *LocalWorkspace) SaveStackSettings(
	ctx context.Context,
	stackName string,
	settings *workspace.ProjectStack,
) error

SaveStackSettings overwrites the settings object for the stack matching the specified stack name. LocalWorkspace writes this value to a Pulumi.<stack>.yaml file in Workspace.WorkDir()

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackNameA := FullyQualifiedStackName("org", "proj", "stackA")
// read existing stack settings for stackA if any
ss, err := w.StackSettings(ctx, stackNameA)
if err != nil {
	// no pulumi.stackA.yaml was found, so create a default
	ss = &workspace.ProjectStack{}
}
stackNameB := FullyQualifiedStackName("org", "proj", "stackB")
// copy the settings to stackB
w.SaveStackSettings(ctx, stackNameB, ss)
Output:

func (*LocalWorkspace) SelectStack

func (l *LocalWorkspace) SelectStack(ctx context.Context, stackName string) error

SelectStack selects and sets an existing stack matching the stack name, failing if none exists.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackName := FullyQualifiedStackName("org", "proj", "existing_stack")
_ = w.SelectStack(ctx, stackName)
Output:

func (*LocalWorkspace) SerializeArgsForOp

func (l *LocalWorkspace) SerializeArgsForOp(ctx context.Context, stackName string) ([]string, error)

SerializeArgsForOp is hook to provide additional args to every CLI commands before they are executed. Provided with stack name, returns a list of args to append to an invoked command ["--config=...", ] LocalWorkspace does not utilize this extensibility point.

func (*LocalWorkspace) SetAllConfig

func (l *LocalWorkspace) SetAllConfig(ctx context.Context, stackName string, config ConfigMap) error

SetAllConfig sets all values in the provided config map for the specified stack name. LocalWorkspace writes the config to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackNameA := FullyQualifiedStackName("org", "proj", "stackA")
// get the last deployed config from stack A
// this overwrites config in pulumi.stackA.yaml
cfg, _ := w.RefreshConfig(ctx, stackNameA)
// add a key to the ConfigMap
cfg["addition_config_key"] = ConfigValue{Value: "additional_config_value"}
// create a new stack
stackNameB := FullyQualifiedStackName("org", "proj", "stackB")
w.CreateStack(ctx, stackNameB)
// save the modified config to stackB
w.SetAllConfig(ctx, stackNameB, cfg)
Output:

func (*LocalWorkspace) SetAllConfigWithOptions added in v3.60.1

func (l *LocalWorkspace) SetAllConfigWithOptions(
	ctx context.Context, stackName string, config ConfigMap, opts *ConfigOptions,
) error

SetAllConfigWithOptions sets all values in the provided config map for the specified stack name using the optional ConfigOptions. LocalWorkspace writes the config to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().

func (*LocalWorkspace) SetConfig

func (l *LocalWorkspace) SetConfig(ctx context.Context, stackName string, key string, val ConfigValue) error

SetConfig sets the specified key-value pair on the provided stack name. LocalWorkspace writes this value to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().

func (*LocalWorkspace) SetConfigWithOptions added in v3.60.1

func (l *LocalWorkspace) SetConfigWithOptions(
	ctx context.Context, stackName string, key string, val ConfigValue, opts *ConfigOptions,
) error

SetConfigWithOptions sets the specified key-value pair on the provided stack name using the optional ConfigOptions. LocalWorkspace writes this value to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().

func (*LocalWorkspace) SetEnvVar

func (l *LocalWorkspace) SetEnvVar(key, value string)

SetEnvVar sets the specified environment value scoped to the current workspace. This value will be passed to all Workspace and Stack level commands.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// set the environment value on the workspace for the stack
w.SetEnvVar("FOO", "bar")
Output:

func (*LocalWorkspace) SetEnvVars

func (l *LocalWorkspace) SetEnvVars(envvars map[string]string) error

SetEnvVars sets the specified map of environment values scoped to the current workspace. These values will be passed to all Workspace and Stack level commands.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// set the environment values on the workspace for the stack
e := map[string]string{
	"FOO": "bar",
}
w.SetEnvVars(e)
Output:

func (*LocalWorkspace) SetProgram

func (l *LocalWorkspace) SetProgram(fn pulumi.RunFunc)

SetProgram sets the program associated with the Workspace to the specified `pulumi.RunFunc`.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
program := func(pCtx *pulumi.Context) error {
	pCtx.Export("an output", pulumi.String("an output value"))
	return nil
}
// this program will be used for all Stack.Update and Stack.Preview operations going forward
w.SetProgram(program)
Output:

func (*LocalWorkspace) SetTag added in v3.57.0

func (l *LocalWorkspace) SetTag(ctx context.Context, stackName string, key string, value string) error

SetTag sets the specified key-value pair on the provided stack name.

func (*LocalWorkspace) Stack

func (l *LocalWorkspace) Stack(ctx context.Context) (*StackSummary, error)

Stack returns a summary of the currently selected stack, if any.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
s, _ := w.Stack(ctx)
fmt.Println(s.UpdateInProgress)
Output:

func (*LocalWorkspace) StackOutputs added in v3.2.0

func (l *LocalWorkspace) StackOutputs(ctx context.Context, stackName string) (OutputMap, error)

StackOutputs gets the current set of Stack outputs from the last Stack.Up().

func (*LocalWorkspace) StackSettings

func (l *LocalWorkspace) StackSettings(ctx context.Context, stackName string) (*workspace.ProjectStack, error)

StackSettings returns the settings object for the stack matching the specified stack name if any. LocalWorkspace reads this from a Pulumi.<stack>.yaml file in Workspace.WorkDir().

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
stackNameA := FullyQualifiedStackName("org", "proj", "stackA")
// read existing stack settings for stackA if any
ss, err := w.StackSettings(ctx, stackNameA)
if err != nil {
	// no pulumi.stackA.yaml was found, so create a default
	ss = &workspace.ProjectStack{}
}
stackNameB := FullyQualifiedStackName("org", "proj", "stackB")
// copy the settings to stackB
w.SaveStackSettings(ctx, stackNameB, ss)
Output:

func (*LocalWorkspace) UnsetEnvVar

func (l *LocalWorkspace) UnsetEnvVar(key string)

UnsetEnvVar unsets the specified environment value scoped to the current workspace. This value will be removed from all Workspace and Stack level commands.

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
// set the environment value on the workspace for the stack
w.SetEnvVar("FOO", "bar")
// unset the environment value on the workspace for the stack
w.UnsetEnvVar("FOO")
Output:

func (*LocalWorkspace) WhoAmI

func (l *LocalWorkspace) WhoAmI(ctx context.Context) (string, error)

WhoAmI returns the currently authenticated user

Example
ctx := context.Background()
// create a workspace from a local project
w, _ := NewLocalWorkspace(ctx, WorkDir(filepath.Join(".", "program")))
user, _ := w.WhoAmI(ctx)
fmt.Println(user)
Output:

func (*LocalWorkspace) WhoAmIDetails added in v3.58.0

func (l *LocalWorkspace) WhoAmIDetails(ctx context.Context) (WhoAmIResult, error)

WhoAmIDetails returns detailed information about the currently logged-in Pulumi identity.

func (*LocalWorkspace) WorkDir

func (l *LocalWorkspace) WorkDir() string

WorkDir returns the working directory to run Pulumi CLI commands. LocalWorkspace expects that this directory contains a Pulumi.yaml file. For "Inline" Pulumi programs created from NewStackInlineSource, a Pulumi.yaml is created on behalf of the user if none is specified.

type LocalWorkspaceOption

type LocalWorkspaceOption interface {
	// contains filtered or unexported methods
}

LocalWorkspaceOption is used to customize and configure a LocalWorkspace at initialization time. See Workdir, Program, PulumiHome, Project, Stacks, and Repo for concrete options.

func EnvVars

func EnvVars(envvars map[string]string) LocalWorkspaceOption

EnvVars is a map of environment values scoped to the workspace. These values will be passed to all Workspace and Stack level commands.

func Program

func Program(program pulumi.RunFunc) LocalWorkspaceOption

Program is the Pulumi Program to execute. If none is supplied, the program identified in $WORKDIR/Pulumi.yaml will be used instead.

func Project

func Project(settings workspace.Project) LocalWorkspaceOption

Project sets project settings for the workspace.

func Pulumi added in v3.104.0

func Pulumi(pulumi PulumiCommand) LocalWorkspaceOption

PulumiCommand is the PulumiCommand instance to use. If none is supplied, the workspace will create an instance using the PulumiCommand CLI found in $PATH.

func PulumiHome

func PulumiHome(dir string) LocalWorkspaceOption

PulumiHome overrides the metadata directory for pulumi commands.

func Repo

func Repo(gitRepo GitRepo) LocalWorkspaceOption

Repo is a git repo with a Pulumi Project to clone into the WorkDir.

func SecretsProvider

func SecretsProvider(secretsProvider string) LocalWorkspaceOption

SecretsProvider is the secrets provider to use with the current workspace when interacting with a stack

func Stacks

Stacks is a list of stack settings objects to seed the workspace.

func WorkDir

func WorkDir(workDir string) LocalWorkspaceOption

WorkDir is the directory to execute commands from and store state.

type OutputMap

type OutputMap map[string]OutputValue

OutputMap is the output result of running a Pulumi program

type OutputValue

type OutputValue struct {
	Value  interface{}
	Secret bool
}

OutputValue models a Pulumi Stack output, providing the plaintext value and a boolean indicating secretness.

type PreviewResult

type PreviewResult struct {
	StdOut        string
	StdErr        string
	ChangeSummary map[apitype.OpType]int
}

PreviewResult is the output of Stack.Preview() describing the expected set of changes from the next Stack.Up()

func (pr *PreviewResult) GetPermalink() (string, error)

GetPermalink returns the permalink URL in the Pulumi Console for the preview operation.

type PreviewStep

type PreviewStep struct {
	// Op is the kind of operation being performed.
	Op string `json:"op"`
	// URN is the resource being affected by this operation.
	URN resource.URN `json:"urn"`
	// Provider is the provider that will perform this step.
	Provider string `json:"provider,omitempty"`
	// OldState is the old state for this resource, if appropriate given the operation type.
	OldState *apitype.ResourceV3 `json:"oldState,omitempty"`
	// NewState is the new state for this resource, if appropriate given the operation type.
	NewState *apitype.ResourceV3 `json:"newState,omitempty"`
	// DiffReasons is a list of keys that are causing a diff (for updating steps only).
	DiffReasons []resource.PropertyKey `json:"diffReasons,omitempty"`
	// ReplaceReasons is a list of keys that are causing replacement (for replacement steps only).
	ReplaceReasons []resource.PropertyKey `json:"replaceReasons,omitempty"`
	// DetailedDiff is a structured diff that indicates precise per-property differences.
	DetailedDiff map[string]PropertyDiff `json:"detailedDiff"`
}

PreviewStep is a summary of the expected state transition of a given resource based on running the current program.

type PropertyDiff

type PropertyDiff struct {
	// Kind is the kind of difference.
	Kind string `json:"kind"`
	// InputDiff is true if this is a difference between old and new inputs instead of old state and new inputs.
	InputDiff bool `json:"inputDiff"`
}

PropertyDiff contains information about the difference in a single property value.

type PulumiCommand added in v3.104.0

type PulumiCommand interface {
	Run(ctx context.Context,
		workdir string,
		stdin io.Reader,
		additionalOutput []io.Writer,
		additionalErrorOutput []io.Writer,
		additionalEnv []string,
		args ...string) (string, string, int, error)
	Version() semver.Version
}

PulumiCommand manages the Pulumi CLI and runs operations.

func InstallPulumiCommand added in v3.104.0

func InstallPulumiCommand(ctx context.Context, opts *PulumiCommandOptions) (
	PulumiCommand,
	error,
)

InstallPulumiCommand downloads and installs the Pulumi CLI. By default the CLI version matching the current SDK release is installed in $HOME/.pulumi/versions/$VERSION. Set `opts.Root` to specify a different directory, and `opts.Version` to install a custom version.

func NewPulumiCommand added in v3.104.0

func NewPulumiCommand(opts *PulumiCommandOptions) (PulumiCommand, error)

NewPulumiCommand creates a Pulumi instance that uses the installation in `opts.Root`. Defaults to using the Pulumi binary found in $PATH if no installation root is specified. If `opts.Version` is specified, it validates that the CLI is compatible with the requested version and throws an error if not. This validation can be skipped by setting the environment variable `PULUMI_AUTOMATION_API_SKIP_VERSION_CHECK` or setting `opts.SkipVersionCheck` to `true`. Note that the environment variable always takes precedence. If it is set it is not possible to re-enable the validation with `opts.SkipVersionCheck`.

type PulumiCommandOptions added in v3.104.0

type PulumiCommandOptions struct {
	// Version is the version to install or validate.
	Version semver.Version
	// Root sets the directory where the CLI should be installed to, or from
	// where the CLI should be retrieved.
	Root string
	// SkipVersionCheck is used to disable the validation of the found Pulumi
	// binary.
	SkipVersionCheck bool
}

type RefreshResult

type RefreshResult struct {
	StdOut  string
	StdErr  string
	Summary UpdateSummary
}

RefreshResult is the output of a successful Stack.Refresh operation

func (rr *RefreshResult) GetPermalink() (string, error)

GetPermalink returns the permalink URL in the Pulumi Console for the refresh operation.

type RemoteStack added in v3.45.0

type RemoteStack struct {
	// contains filtered or unexported fields
}

RemoteStack is an isolated, independently configurable instance of a Pulumi program that is operated on remotely (up/preview/refresh/destroy).

func NewRemoteStackGitSource added in v3.45.0

func NewRemoteStackGitSource(
	ctx context.Context,
	stackName string, repo GitRepo,
	opts ...RemoteWorkspaceOption,
) (RemoteStack, error)

PREVIEW: NewRemoteStackGitSource creates a Stack backed by a RemoteWorkspace with source code from the specified GitRepo. Pulumi operations on the stack (Preview, Update, Refresh, and Destroy) are performed remotely.

func SelectRemoteStackGitSource added in v3.45.0

func SelectRemoteStackGitSource(
	ctx context.Context,
	stackName string, repo GitRepo,
	opts ...RemoteWorkspaceOption,
) (RemoteStack, error)

PREVIEW: SelectRemoteStackGitSource selects an existing Stack backed by a RemoteWorkspace with source code from the specified GitRepo. Pulumi operations on the stack (Preview, Update, Refresh, and Destroy) are performed remotely.

func UpsertRemoteStackGitSource added in v3.45.0

func UpsertRemoteStackGitSource(
	ctx context.Context,
	stackName string, repo GitRepo,
	opts ...RemoteWorkspaceOption,
) (RemoteStack, error)

PREVIEW: UpsertRemoteStackGitSource creates a Stack backed by a RemoteWorkspace with source code from the specified GitRepo. If the Stack already exists, it will not error and proceed with returning the Stack. Pulumi operations on the stack (Preview, Update, Refresh, and Destroy) are performed remotely.

func (*RemoteStack) Cancel added in v3.45.0

func (s *RemoteStack) Cancel(ctx context.Context) error

Cancel stops a stack's currently running update. It returns an error if no update is currently running. Note that this operation is _very dangerous_, and may leave the stack in an inconsistent state if a resource operation was pending when the update was canceled. This command is not supported for diy backends.

func (*RemoteStack) Destroy added in v3.45.0

Destroy deletes all resources in a stack, leaving all history and configuration intact. This operation runs remotely.

func (*RemoteStack) Export added in v3.45.0

Export exports the deployment state of the stack. This can be combined with Stack.Import to edit a stack's state (such as recovery from failed deployments).

func (*RemoteStack) History added in v3.45.0

func (s *RemoteStack) History(ctx context.Context, pageSize, page int) ([]UpdateSummary, error)

History returns a list summarizing all previous and current results from Stack lifecycle operations (up/preview/refresh/destroy).

func (*RemoteStack) Import added in v3.45.0

func (s *RemoteStack) Import(ctx context.Context, state apitype.UntypedDeployment) error

Import imports the specified deployment state into the stack. This can be combined with Stack.Export to edit a stack's state (such as recovery from failed deployments).

func (*RemoteStack) Name added in v3.45.0

func (s *RemoteStack) Name() string

Name returns the stack name.

func (*RemoteStack) Outputs added in v3.45.0

func (s *RemoteStack) Outputs(ctx context.Context) (OutputMap, error)

Outputs get the current set of Stack outputs from the last Stack.Up().

func (*RemoteStack) Preview added in v3.45.0

Preview preforms a dry-run update to a stack, returning pending changes. https://www.pulumi.com/docs/cli/commands/pulumi_preview/ This operation runs remotely.

func (*RemoteStack) Refresh added in v3.45.0

Refresh compares the current stack’s resource state with the state known to exist in the actual cloud provider. Any such changes are adopted into the current stack. This operation runs remotely.

func (*RemoteStack) Up added in v3.45.0

func (s *RemoteStack) Up(ctx context.Context, opts ...optremoteup.Option) (UpResult, error)

Up creates or updates the resources in a stack by executing the program in the Workspace. https://www.pulumi.com/docs/cli/commands/pulumi_up/ This operation runs remotely.

type RemoteWorkspaceOption added in v3.45.0

type RemoteWorkspaceOption interface {
	// contains filtered or unexported methods
}

LocalWorkspaceOption is used to customize and configure a LocalWorkspace at initialization time. See Workdir, Program, PulumiHome, Project, Stacks, and Repo for concrete options.

func RemoteEnvVars added in v3.45.0

func RemoteEnvVars(envvars map[string]EnvVarValue) RemoteWorkspaceOption

RemoteEnvVars is a map of environment values scoped to the remote workspace. These will be passed to remote operations.

func RemoteExecutorImage added in v3.111.0

func RemoteExecutorImage(image *ExecutorImage) RemoteWorkspaceOption

RemoteExecutorImage sets the image to use for the remote executor.

func RemotePreRunCommands added in v3.45.0

func RemotePreRunCommands(commands ...string) RemoteWorkspaceOption

RemotePreRunCommands is an optional list of arbitrary commands to run before the remote Pulumi operation is invoked.

func RemoteSkipInstallDependencies added in v3.50.0

func RemoteSkipInstallDependencies(skipInstallDependencies bool) RemoteWorkspaceOption

RemoteSkipInstallDependencies sets whether to skip the default dependency installation step. Defaults to false.

type SetupFn

type SetupFn func(context.Context, Workspace) error

SetupFn is a function to execute after enlisting in a git repo. It is called with the workspace after all other options have been processed.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("myOrg", "nodejs_project", "myStack")

repo := GitRepo{
	URL:         "https://some.example.repo.git",
	ProjectPath: "goproj",
	// this call back will get executed post-clone to allow for additional program setup
	Setup: func(ctx context.Context, workspace Workspace) error {
		// restore node dependencies required to run the program
		cmd := exec.Command("npm", "install")
		cmd.Dir = workspace.WorkDir()
		return cmd.Run()
	},
}

// initialize a stack from the git repo
NewStackRemoteSource(ctx, stackName, repo)
Output:

type Stack

type Stack struct {
	// contains filtered or unexported fields
}

Stack is an isolated, independently configurable instance of a Pulumi program. Stack exposes methods for the full pulumi lifecycle (up/preview/refresh/destroy), as well as managing configuration. Multiple Stacks are commonly used to denote different phases of development (such as development, staging and production) or feature branches (such as feature-x-dev, jane-feature-x-dev).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "dev_stack")
cfg := ConfigMap{
	"bar": ConfigValue{
		Value: "abc",
	},
	"buzz": ConfigValue{
		Value:  "secret",
		Secret: true,
	},
}

// initialize
pDir := filepath.Join(".", "project")
s, err := NewStackLocalSource(ctx, stackName, pDir)
if err != nil {
	// Handle failure creating stack.
}

defer func() {
	// Workspace operations can be accessed via Stack.Workspace()
	// -- pulumi stack rm --
	err = s.Workspace().RemoveStack(ctx, s.Name())
}()

err = s.SetAllConfig(ctx, cfg)
if err != nil {
	// Handle failure setting configurations.
}

// -- pulumi up --
res, err := s.Up(ctx)
if err != nil {
	// Handle failure updating stack.
}
fmt.Println(len(res.Outputs))

// -- pulumi preview --

prev, err := s.Preview(ctx)
if err != nil {
	// Handle failure previewing stack.
}
// no changes after the update
fmt.Println(prev.ChangeSummary["same"])

// -- pulumi refresh --

ref, err := s.Refresh(ctx)
if err != nil {
	// Handle error during refresh.
}
// Success!
fmt.Println(ref.Summary.Result)

// -- pulumi destroy --

_, err = s.Destroy(ctx)
if err != nil {
	// Handle error during destroy.
}
Output:

func NewStack

func NewStack(ctx context.Context, stackName string, ws Workspace) (Stack, error)

NewStack creates a new stack using the given workspace, and stack name. It fails if a stack with that name already exists

Example
ctx := context.Background()
w, err := NewLocalWorkspace(ctx)
if err != nil {
	// Handle error creating workspace.
}

stackName := FullyQualifiedStackName("org", "proj", "stack")
stack, err := NewStack(ctx, stackName, w)
if err != nil {
	// Handle error creating stack.
}
_, err = stack.Up(ctx)
if err != nil {
	// Handle error updating stack.
}
Output:

func NewStackInlineSource

func NewStackInlineSource(
	ctx context.Context,
	stackName string,
	projectName string,
	program pulumi.RunFunc,
	opts ...LocalWorkspaceOption,
) (Stack, error)

NewStackInlineSource creates a Stack backed by a LocalWorkspace created on behalf of the user, with the specified program. If no Project option is specified, default project settings will be created on behalf of the user. Similarly, unless a WorkDir option is specified, the working directory will default to a new temporary directory provided by the OS.

Example
ctx := context.Background()
projName := "proj"
stackName := FullyQualifiedStackName("myOrg", projName, "stack")
// create a new Stack with a default ProjectSettings file, and a temporary WorkDir created in a new
// LocalWorkspace on behalf of the user.
stack, _ := NewStackInlineSource(ctx, stackName, projName, func(pCtx *pulumi.Context) error {
	pCtx.Export("outputA", pulumi.String("valueA"))
	return nil
})
// Stack.Up runs the inline pulumi.RunFunc specified above.
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
stack.Up(ctx)
Output:

func NewStackLocalSource

func NewStackLocalSource(ctx context.Context, stackName, workDir string, opts ...LocalWorkspaceOption) (Stack, error)

NewStackLocalSource creates a Stack backed by a LocalWorkspace created on behalf of the user, from the specified WorkDir. This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("myOrg", "proj", "stack")
workDir := filepath.Join(".", "program", "dir")
// creates a new stack with a new LocalWorkspace created from provided WorkDir. This Workspace will pick up
// any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml)
stack, _ := NewStackLocalSource(ctx, stackName, workDir)
// Stack.Up runs the program in workDir
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
// Stack.Up now runs our inline program
stack.Up(ctx)
Output:

func NewStackRemoteSource

func NewStackRemoteSource(
	ctx context.Context,
	stackName string,
	repo GitRepo,
	opts ...LocalWorkspaceOption,
) (Stack, error)

NewStackRemoteSource creates a Stack backed by a LocalWorkspace created on behalf of the user, with source code cloned from the specified GitRepo. This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml) that are cloned into the Workspace. Unless a WorkDir option is specified, the GitRepo will be clone into a new temporary directory provided by the OS.

Example
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

// we'll compile a the program into an executable with the name "examplesBinary"
binName := "examplesBinary"
// a description of the git repo to clone
repo := GitRepo{
	URL: "https://github.com/pulumi/test-repo.git",
	// the subdirectory relative to the root of the repo
	ProjectPath: "goproj",
	// this call back will get executed post-clone to allow for additional program setup
	Setup: func(ctx context.Context, workspace Workspace) error {
		cmd := exec.Command("go", "build", "-o", binName, "main.go")
		cmd.Dir = workspace.WorkDir()
		return cmd.Run()
	},
}
// an override to the project file in the git repo, specifying our pre-built executable
project := workspace.Project{
	Name: tokens.PackageName(pName),
	Runtime: workspace.NewProjectRuntimeInfo("go", map[string]interface{}{
		"binary": binName,
	}),
}

// initialize a stack from the git repo, specifying our project override
NewStackRemoteSource(ctx, stackName, repo, Project(project))
Output:

func SelectStack

func SelectStack(ctx context.Context, stackName string, ws Workspace) (Stack, error)

SelectStack selects stack using the given workspace, and stack name. It returns an error if the given Stack does not exist.

func SelectStackInlineSource

func SelectStackInlineSource(
	ctx context.Context,
	stackName string,
	projectName string,
	program pulumi.RunFunc,
	opts ...LocalWorkspaceOption,
) (Stack, error)

SelectStackInlineSource selects an existing Stack backed by a new LocalWorkspace created on behalf of the user, with the specified program. If no Project option is specified, default project settings will be created on behalf of the user. Similarly, unless a WorkDir option is specified, the working directory will default to a new temporary directory provided by the OS.

Example
ctx := context.Background()
projName := "proj"
stackName := FullyQualifiedStackName("myOrg", projName, "existing_stack")
// selects an existing stack with a default ProjectSettings file, and a temporary WorkDir in a new LocalWorkspace
// created on behalf of the user.
stack, _ := SelectStackInlineSource(ctx, stackName, projName, func(pCtx *pulumi.Context) error {
	pCtx.Export("outputA", pulumi.String("valueA"))
	return nil
})
// Stack.Up runs the inline pulumi.RunFunc specified above.
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
stack.Up(ctx)
Output:

func SelectStackLocalSource

func SelectStackLocalSource(
	ctx context.Context,
	stackName,
	workDir string,
	opts ...LocalWorkspaceOption,
) (Stack, error)

SelectStackLocalSource selects an existing Stack backed by a LocalWorkspace created on behalf of the user, from the specified WorkDir. This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("myOrg", "proj", "stack")
workDir := filepath.Join(".", "program", "dir")
// selects an existing stack with a new LocalWorkspace created from provided WorkDir. This Workspace will pick up
// any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml)
stack, _ := SelectStackLocalSource(ctx, stackName, workDir)
// Stack.Up runs the program in workDir
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
// Stack.Up now runs our inline program
stack.Up(ctx)
Output:

func SelectStackRemoteSource

func SelectStackRemoteSource(
	ctx context.Context,
	stackName string, repo GitRepo,
	opts ...LocalWorkspaceOption,
) (Stack, error)

SelectStackRemoteSource selects an existing Stack backed by a LocalWorkspace created on behalf of the user, with source code cloned from the specified GitRepo. This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml) that are cloned into the Workspace. Unless a WorkDir option is specified, the GitRepo will be clone into a new temporary directory provided by the OS.

Example
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

// we'll compile a the program into an executable with the name "examplesBinary"
binName := "examplesBinary"
// a description of the git repo to clone
repo := GitRepo{
	URL: "https://github.com/pulumi/test-repo.git",
	// the subdirectory relative to the root of the repo
	ProjectPath: "goproj",
	// this call back will get executed post-clone to allow for additional program setup
	Setup: func(ctx context.Context, workspace Workspace) error {
		cmd := exec.Command("go", "build", "-o", binName, "main.go")
		cmd.Dir = workspace.WorkDir()
		return cmd.Run()
	},
}
// an override to the project file in the git repo, specifying our pre-built executable
project := workspace.Project{
	Name: tokens.PackageName(pName),
	Runtime: workspace.NewProjectRuntimeInfo("go", map[string]interface{}{
		"binary": binName,
	}),
}

// select an existing stack using a LocalWorkspace created from the git repo, specifying our project override
SelectStackRemoteSource(ctx, stackName, repo, Project(project))
Output:

func UpsertStack

func UpsertStack(ctx context.Context, stackName string, ws Workspace) (Stack, error)

UpsertStack tries to select a stack using the given workspace and stack name, or falls back to trying to create the stack if it does not exist.

Example
ctx := context.Background()
w, err := NewLocalWorkspace(ctx)
if err != nil {
	// Handle error creating workspace.
}

stackName := FullyQualifiedStackName("org", "proj", "stack")
stack, err := UpsertStack(ctx, stackName, w)
if err != nil {
	// Handle error creating/updating stack.
}
_, err = stack.Up(ctx)
if err != nil {
	// Handle error during update.
}
Output:

func UpsertStackInlineSource

func UpsertStackInlineSource(
	ctx context.Context,
	stackName string,
	projectName string,
	program pulumi.RunFunc,
	opts ...LocalWorkspaceOption,
) (Stack, error)

UpsertStackInlineSource creates a Stack backed by a LocalWorkspace created on behalf of the user, with the specified program. If the Stack already exists, it will not error and proceed to selecting the Stack. If no Project option is specified, default project settings will be created on behalf of the user. Similarly, unless a WorkDir option is specified, the working directory will default to a new temporary directory provided by the OS.

Example
ctx := context.Background()
projName := "proj"
stackName := FullyQualifiedStackName("myOrg", "proj", "stack")
// create or select a new Stack with a default ProjectSettings file, and a temporary WorkDir created in a new
// LocalWorkspace on behalf of the user.
stack, _ := UpsertStackInlineSource(ctx, stackName, projName, func(pCtx *pulumi.Context) error {
	pCtx.Export("outputA", pulumi.String("valueA"))
	return nil
})
// Stack.Up runs the inline pulumi.RunFunc specified above.
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
stack.Up(ctx)
Output:

func UpsertStackLocalSource

func UpsertStackLocalSource(
	ctx context.Context,
	stackName,
	workDir string,
	opts ...LocalWorkspaceOption,
) (Stack, error)

UpsertStackLocalSource creates a Stack backed by a LocalWorkspace created on behalf of the user, from the specified WorkDir. If the Stack already exists, it will not error and proceed to selecting the Stack.This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("myOrg", "proj", "stack")
workDir := filepath.Join(".", "program", "dir")
// create or select a new stack with a new LocalWorkspace created from provided WorkDir. This Workspace will pick up
// any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml)
stack, _ := UpsertStackLocalSource(ctx, stackName, workDir)
// Stack.Up runs the program in workDir
stack.Up(ctx)
// we can update the Workspace program for subsequent updates if desired
stack.Workspace().SetProgram(func(pCtx *pulumi.Context) error {
	pCtx.Export("outputAA", pulumi.String("valueAA"))
	return nil
})
// Stack.Up now runs our inline program
stack.Up(ctx)
Output:

func UpsertStackRemoteSource

func UpsertStackRemoteSource(
	ctx context.Context, stackName string, repo GitRepo, opts ...LocalWorkspaceOption,
) (Stack, error)

UpsertStackRemoteSource creates a Stack backed by a LocalWorkspace created on behalf of the user, with source code cloned from the specified GitRepo. If the Stack already exists, it will not error and proceed to selecting the Stack. This Workspace will pick up any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml) that are cloned into the Workspace. Unless a WorkDir option is specified, the GitRepo will be clone into a new temporary directory provided by the OS.

Example
ctx := context.Background()
pName := "go_remote_proj"
stackName := FullyQualifiedStackName("myOrg", pName, "myStack")

// we'll compile a the program into an executable with the name "examplesBinary"
binName := "examplesBinary"
// a description of the git repo to clone
repo := GitRepo{
	URL: "https://github.com/pulumi/test-repo.git",
	// the subdirectory relative to the root of the repo
	ProjectPath: "goproj",
	// this call back will get executed post-clone to allow for additional program setup
	Setup: func(ctx context.Context, workspace Workspace) error {
		cmd := exec.Command("go", "build", "-o", binName, "main.go")
		cmd.Dir = workspace.WorkDir()
		return cmd.Run()
	},
}
// an override to the project file in the git repo, specifying our pre-built executable
project := workspace.Project{
	Name: tokens.PackageName(pName),
	Runtime: workspace.NewProjectRuntimeInfo("go", map[string]interface{}{
		"binary": binName,
	}),
}

// initialize or select a stack from the git repo, specifying our project override
UpsertStackRemoteSource(ctx, stackName, repo, Project(project))
Output:

func (*Stack) AddEnvironments added in v3.97.0

func (s *Stack) AddEnvironments(ctx context.Context, envs ...string) error

AddEnvironments adds environments to the end of a stack's import list. Imported environments are merged in order per the ESC merge rules. The list of environments behaves as if it were the import list in an anonymous environment.

func (*Stack) Cancel

func (s *Stack) Cancel(ctx context.Context) error

Cancel stops a stack's currently running update. It returns an error if no update is currently running. Note that this operation is _very dangerous_, and may leave the stack in an inconsistent state if a resource operation was pending when the update was canceled. This command is not supported for diy backends.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// attempt to cancel the in progress operation
// note that this operation is _very dangerous_, and may leave the stack in an inconsistent state.
_ = stack.Cancel(ctx)
Output:

func (*Stack) ChangeSecretsProvider added in v3.97.0

func (s *Stack) ChangeSecretsProvider(
	ctx context.Context, newSecretsProvider string, opts *ChangeSecretsProviderOptions,
) error

ChangeSecretsProvider edits the secrets provider for the stack.

func (*Stack) Destroy

func (s *Stack) Destroy(ctx context.Context, opts ...optdestroy.Option) (DestroyResult, error)

Destroy deletes all resources in a stack, leaving all history and configuration intact.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// select an existing stack to destroy
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
stack.Destroy(ctx, optdestroy.Message("a message to save with the destroy operation"))
Output:

Example (StreamingProgress)
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// select an existing stack to destroy
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// create a temp file that we can tail during while our program runs
tmp, _ := os.CreateTemp(os.TempDir(), "")
// optdestroy.ProgressStreams allows us to stream incremental output to stdout, a file to tail, etc.
// this gives us incremental status over time
progressStreams := []io.Writer{os.Stdout, tmp}
// this destroy will incrementally stream unstructured progress messages to stdout and our temp file
stack.Destroy(ctx, optdestroy.ProgressStreams(progressStreams...))
Output:

func (*Stack) Export

func (s *Stack) Export(ctx context.Context) (apitype.UntypedDeployment, error)

Export exports the deployment state of the stack. This can be combined with Stack.Import to edit a stack's state (such as recovery from failed deployments).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
dep, _ := stack.Export(ctx)
// import/export is backwards compatible, and we must write code specific to the version we're dealing with.
if dep.Version != 3 {
	panic("expected deployment version 3")
}
var state apitype.DeploymentV3
_ = json.Unmarshal(dep.Deployment, &state)

// ... perform edits on the state ...

// marshal out updated deployment state
bytes, _ := json.Marshal(state)
dep.Deployment = bytes
// import our edited deployment state back to our stack
_ = stack.Import(ctx, dep)
Output:

func (*Stack) GetAllConfig

func (s *Stack) GetAllConfig(ctx context.Context) (ConfigMap, error)

GetAllConfig returns the full config map.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
cfg, _ := stack.GetAllConfig(ctx)
fmt.Println(cfg["config_key"].Value)
fmt.Println(cfg["config_key"].Secret)
Output:

func (*Stack) GetConfig

func (s *Stack) GetConfig(ctx context.Context, key string) (ConfigValue, error)

GetConfig returns the config value associated with the specified key.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
cfgVal, _ := stack.GetConfig(ctx, "config_key")
fmt.Println(cfgVal.Value)
fmt.Println(cfgVal.Secret)
Output:

func (*Stack) GetConfigWithOptions added in v3.60.1

func (s *Stack) GetConfigWithOptions(ctx context.Context, key string, opts *ConfigOptions) (ConfigValue, error)

GetConfigWithOptions returns the config value associated with the specified key using the optional ConfigOptions.

func (*Stack) GetTag added in v3.57.0

func (s *Stack) GetTag(ctx context.Context, key string) (string, error)

GetTag returns the tag value associated with specified key.

func (*Stack) History

func (s *Stack) History(ctx context.Context,
	pageSize int, page int, opts ...opthistory.Option,
) ([]UpdateSummary, error)

History returns a list summarizing all previous and current results from Stack lifecycle operations (up/preview/refresh/destroy).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
pageSize := 0 // fetch all history entries, don't paginate
page := 0     // fetch all history entries, don't paginate
hist, _ := stack.History(ctx, pageSize, page)
// last operation start time
fmt.Println(hist[0].StartTime)
Output:

func (*Stack) Import

func (s *Stack) Import(ctx context.Context, state apitype.UntypedDeployment) error

Import imports the specified deployment state into the stack. This can be combined with Stack.Export to edit a stack's state (such as recovery from failed deployments).

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
dep, _ := stack.Export(ctx)
// import/export is backwards compatible, and we must write code specific to the version we're dealing with.
if dep.Version != 3 {
	panic("expected deployment version 3")
}
var state apitype.DeploymentV3
_ = json.Unmarshal(dep.Deployment, &state)

// ... perform edits on the state ...

// marshal out updated deployment state
bytes, _ := json.Marshal(state)
dep.Deployment = bytes
// import our edited deployment state back to our stack
_ = stack.Import(ctx, dep)
Output:

func (*Stack) Info

func (s *Stack) Info(ctx context.Context) (StackSummary, error)

Info returns a summary of the Stack including its URL.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
info, _ := stack.Info(ctx)
// url to view the Stack in the Pulumi SaaS or other backend
fmt.Println(info.URL)
Output:

func (*Stack) ListEnvironments added in v3.100.0

func (s *Stack) ListEnvironments(ctx context.Context) ([]string, error)

ListEnvironments returns the list of environments from the stack's configuration.

func (*Stack) ListTags added in v3.57.0

func (s *Stack) ListTags(ctx context.Context) (map[string]string, error)

ListTags returns the full key-value tag map associated with the stack.

func (*Stack) Name

func (s *Stack) Name() string

Name returns the stack name

func (*Stack) Outputs

func (s *Stack) Outputs(ctx context.Context) (OutputMap, error)

Outputs get the current set of Stack outputs from the last Stack.Up().

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
outs, _ := stack.Outputs(ctx)
fmt.Println(outs["key"].Value.(string))
fmt.Println(outs["key"].Secret)
Output:

func (*Stack) Preview

func (s *Stack) Preview(ctx context.Context, opts ...optpreview.Option) (PreviewResult, error)

Preview preforms a dry-run update to a stack, returning pending changes. https://www.pulumi.com/docs/cli/commands/pulumi_preview/

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// create a new stack and preview changes
stack, _ := NewStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
stack.Preview(ctx, optpreview.Message("a message to save with the preive operation"))
Output:

func (*Stack) PreviewRefresh added in v3.107.0

func (s *Stack) PreviewRefresh(ctx context.Context, opts ...optrefresh.Option) (PreviewResult, error)

func (*Stack) Refresh

func (s *Stack) Refresh(ctx context.Context, opts ...optrefresh.Option) (RefreshResult, error)

Refresh compares the current stack’s resource state with the state known to exist in the actual cloud provider. Any such changes are adopted into the current stack.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// select an existing stack and refresh the resources under management
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
stack.Refresh(ctx, optrefresh.Message("a message to save with the refresh operation"))
Output:

Example (StreamingProgress)
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// select an existing stack and refresh the resources under management
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// create a temp file that we can tail during while our program runs
tmp, _ := os.CreateTemp(os.TempDir(), "")
// optrefresh.ProgressStreams allows us to stream incremental output to stdout, a file to tail, etc.
// this gives us incremental status over time
progressStreams := []io.Writer{os.Stdout, tmp}
// this refresh will incrementally stream unstructured progress messages to stdout and our temp file
stack.Refresh(ctx, optrefresh.ProgressStreams(progressStreams...))
Output:

func (*Stack) RefreshConfig

func (s *Stack) RefreshConfig(ctx context.Context) (ConfigMap, error)

RefreshConfig gets and sets the config map used with the last Update.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// get the last deployed config from stack and overwrite Pulumi.stack.yaml
_, _ = stack.RefreshConfig(ctx)
Output:

func (*Stack) RemoveAllConfig

func (s *Stack) RemoveAllConfig(ctx context.Context, keys []string) error

RemoveAllConfig removes all values in the provided list of keys.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// remove config matching the specified keys
_ = stack.RemoveAllConfig(ctx, []string{"key0", "key1", "...", "keyN"})
Output:

func (*Stack) RemoveAllConfigWithOptions added in v3.60.1

func (s *Stack) RemoveAllConfigWithOptions(ctx context.Context, keys []string, opts *ConfigOptions) error

RemoveAllConfigWithOptions removes all values in the provided list of keys using the optional ConfigOptions.

func (*Stack) RemoveConfig

func (s *Stack) RemoveConfig(ctx context.Context, key string) error

RemoveConfig removes the specified config key-value pair.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// remove config matching the specified key
_ = stack.RemoveConfig(ctx, "key_to_remove")
Output:

func (*Stack) RemoveConfigWithOptions added in v3.60.1

func (s *Stack) RemoveConfigWithOptions(ctx context.Context, key string, opts *ConfigOptions) error

RemoveConfigWithOptions removes the specified config key-value pair using the optional ConfigOptions.

func (*Stack) RemoveEnvironment added in v3.97.0

func (s *Stack) RemoveEnvironment(ctx context.Context, env string) error

RemoveEnvironment removes an environment from a stack's configuration.

func (*Stack) RemoveTag added in v3.57.0

func (s *Stack) RemoveTag(ctx context.Context, key string) error

RemoveTag removes the specified tag key-value pair from the stack.

func (*Stack) SetAllConfig

func (s *Stack) SetAllConfig(ctx context.Context, config ConfigMap) error

SetAllConfig sets all values in the provided config map.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
cfg := ConfigMap{
	"key0": ConfigValue{Value: "abc", Secret: true},
	"key1": ConfigValue{Value: "def"},
}
// set all config in map
_ = stack.SetAllConfig(ctx, cfg)
Output:

func (*Stack) SetAllConfigWithOptions added in v3.60.1

func (s *Stack) SetAllConfigWithOptions(ctx context.Context, config ConfigMap, opts *ConfigOptions) error

SetAllConfigWithOptions sets all values in the provided config map using the optional ConfigOptions.

func (*Stack) SetConfig

func (s *Stack) SetConfig(ctx context.Context, key string, val ConfigValue) error

SetConfig sets the specified config key-value pair.

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
stack, _ := SelectStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// set config key-value pair
_ = stack.SetConfig(ctx, "key_to_set", ConfigValue{Value: "abc", Secret: true})
Output:

func (*Stack) SetConfigWithOptions added in v3.60.1

func (s *Stack) SetConfigWithOptions(ctx context.Context, key string, val ConfigValue, opts *ConfigOptions) error

SetConfigWithOptions sets the specified config key-value pair using the optional ConfigOptions.

func (*Stack) SetTag added in v3.57.0

func (s *Stack) SetTag(ctx context.Context, key string, value string) error

SetTag sets a tag key-value pair on the stack.

func (*Stack) Up

func (s *Stack) Up(ctx context.Context, opts ...optup.Option) (UpResult, error)

Up creates or updates the resources in a stack by executing the program in the Workspace. https://www.pulumi.com/docs/cli/commands/pulumi_up/

Example
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// create a new stack to update
stack, _ := NewStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
result, _ := stack.Up(ctx, optup.Message("a message to save with the up operation"), optup.Parallel(10000))
permalink, _ := result.GetPermalink()
fmt.Println(permalink)
Output:

Example (StreamingProgress)
ctx := context.Background()
stackName := FullyQualifiedStackName("org", "project", "stack")
// create a new stack to update
stack, _ := NewStackLocalSource(ctx, stackName, filepath.Join(".", "program"))
// create a temp file that we can tail during while our program runs
tmp, _ := os.CreateTemp(os.TempDir(), "")
// optup.ProgressStreams allows us to stream incremental output to stdout, a file to tail, etc.
// this gives us incremental status over time
progressStreams := []io.Writer{os.Stdout, tmp}
// this update will incrementally stream unstructured progress messages to stdout and our temp file
stack.Up(ctx, optup.ProgressStreams(progressStreams...))
Output:

func (*Stack) Workspace

func (s *Stack) Workspace() Workspace

Workspace returns the underlying Workspace backing the Stack. This handles state associated with the Project and child Stacks including settings, configuration, and environment.

type StackSummary

type StackSummary struct {
	Name             string `json:"name"`
	Current          bool   `json:"current"`
	LastUpdate       string `json:"lastUpdate,omitempty"`
	UpdateInProgress bool   `json:"updateInProgress"`
	ResourceCount    *int   `json:"resourceCount,omitempty"`
	URL              string `json:"url,omitempty"`
}

StackSummary is a description of a stack and its current status.

type UpResult

type UpResult struct {
	StdOut  string
	StdErr  string
	Outputs OutputMap
	Summary UpdateSummary
}

UpResult contains information about a Stack.Up operation, including Outputs, and a summary of the deployed changes.

func (ur *UpResult) GetPermalink() (string, error)

GetPermalink returns the permalink URL in the Pulumi Console for the update operation.

type UpdateSummary

type UpdateSummary struct {
	Version     int               `json:"version"`
	Kind        string            `json:"kind"`
	StartTime   string            `json:"startTime"`
	Message     string            `json:"message"`
	Environment map[string]string `json:"environment"`
	Config      ConfigMap         `json:"config"`
	Result      string            `json:"result,omitempty"`

	// These values are only present once the update finishes
	EndTime         *string         `json:"endTime,omitempty"`
	ResourceChanges *map[string]int `json:"resourceChanges,omitempty"`
}

UpdateSummary provides a summary of a Stack lifecycle operation (up/preview/refresh/destroy).

type WhoAmIResult added in v3.58.0

type WhoAmIResult struct {
	User          string   `json:"user"`
	Organizations []string `json:"organizations,omitempty"`
	URL           string   `json:"url"`
}

WhoAmIResult contains detailed information about the currently logged-in Pulumi identity.

type Workspace

type Workspace interface {
	// ProjectSettings returns the settings object for the current project if any.
	ProjectSettings(context.Context) (*workspace.Project, error)
	// SaveProjectSettings overwrites the settings object in the current project.
	// There can only be a single project per workspace. Fails is new project name does not match old.
	SaveProjectSettings(context.Context, *workspace.Project) error
	// StackSettings returns the settings object for the stack matching the specified stack name if any.
	StackSettings(context.Context, string) (*workspace.ProjectStack, error)
	// SaveStackSettings overwrites the settings object for the stack matching the specified stack name.
	SaveStackSettings(context.Context, string, *workspace.ProjectStack) error
	// SerializeArgsForOp is hook to provide additional args to every CLI commands before they are executed.
	// Provided with stack name,
	// returns a list of args to append to an invoked command ["--config=...", ].
	SerializeArgsForOp(context.Context, string) ([]string, error)
	// PostCommandCallback is a hook executed after every command. Called with the stack name.
	// An extensibility point to perform workspace cleanup (CLI operations may create/modify a Pulumi.stack.yaml).
	PostCommandCallback(context.Context, string) error
	// AddEnvironments adds the specified environments to the provided stack's configuration.
	AddEnvironments(context.Context, string, ...string) error
	// ListEnvironments returns the list of environments from the provided stack's configuration.
	ListEnvironments(context.Context, string) ([]string, error)
	// RemoveEnvironment removes the specified environment from the provided stack's configuration.
	RemoveEnvironment(context.Context, string, string) error
	// GetConfig returns the value associated with the specified stack name and key,
	// scoped to the current workspace.
	GetConfig(context.Context, string, string) (ConfigValue, error)
	// GetConfigWithOptions returns the value associated with the specified stack name and key
	// using the optional ConfigOptions,
	// scoped to the current workspace.
	GetConfigWithOptions(context.Context, string, string, *ConfigOptions) (ConfigValue, error)
	// GetAllConfig returns the config map for the specified stack name, scoped to the current workspace.
	GetAllConfig(context.Context, string) (ConfigMap, error)
	// SetConfig sets the specified key-value pair on the provided stack name.
	SetConfig(context.Context, string, string, ConfigValue) error
	// SetConfigWithOptions sets the specified key-value pair on the provided stack name
	// using the optional ConfigOptions.
	SetConfigWithOptions(context.Context, string, string, ConfigValue, *ConfigOptions) error
	// SetAllConfig sets all values in the provided config map for the specified stack name.
	SetAllConfig(context.Context, string, ConfigMap) error
	// SetAllConfigWithOptions sets all values in the provided config map for the specified stack name
	// using the optional ConfigOptions.
	SetAllConfigWithOptions(context.Context, string, ConfigMap, *ConfigOptions) error
	// RemoveConfig removes the specified key-value pair on the provided stack name.
	RemoveConfig(context.Context, string, string) error
	// RemoveConfigWithOptions removes the specified key-value pair on the provided stack name
	// using the optional ConfigOptions.
	RemoveConfigWithOptions(context.Context, string, string, *ConfigOptions) error
	// RemoveAllConfig removes all values in the provided key list for the specified stack name.
	RemoveAllConfig(context.Context, string, []string) error
	// RemoveAllConfigWithOptions removes all values in the provided key list for the specified stack name
	// using the optional ConfigOptions.
	RemoveAllConfigWithOptions(context.Context, string, []string, *ConfigOptions) error
	// RefreshConfig gets and sets the config map used with the last Update for Stack matching stack name.
	RefreshConfig(context.Context, string) (ConfigMap, error)
	// GetTag returns the value associated with the specified stack name and key.
	GetTag(context.Context, string, string) (string, error)
	// SetTag sets the specified key-value pair on the provided stack name.
	SetTag(context.Context, string, string, string) error
	// RemoveTag removes the specified key-value pair on the provided stack name.
	RemoveTag(context.Context, string, string) error
	// ListTags returns the tag map for the specified stack name.
	ListTags(context.Context, string) (map[string]string, error)
	// GetEnvVars returns the environment values scoped to the current workspace.
	GetEnvVars() map[string]string
	// SetEnvVars sets the specified map of environment values scoped to the current workspace.
	// These values will be passed to all Workspace and Stack level commands.
	SetEnvVars(map[string]string) error
	// SetEnvVar sets the specified environment value scoped to the current workspace.
	// This value will be passed to all Workspace and Stack level commands.
	SetEnvVar(string, string)
	// UnsetEnvVar unsets the specified environment value scoped to the current workspace.
	// This value will be removed from all Workspace and Stack level commands.
	UnsetEnvVar(string)
	// WorkDir returns the working directory to run Pulumi CLI commands.
	WorkDir() string
	// PulumiCommand returns the PulumiCommand instance that is used to run PulumiCommand CLI commands.
	PulumiCommand() PulumiCommand
	// PulumiHome returns the directory override for CLI metadata if set.
	// This customizes the location of $PULUMI_HOME where metadata is stored and plugins are installed.
	PulumiHome() string
	// PulumiVersion returns the version of the underlying Pulumi CLI/Engine.
	PulumiVersion() string
	// WhoAmI returns the currently authenticated user.
	WhoAmI(context.Context) (string, error)
	// WhoAmIDetails returns detailed information about the currently
	// logged-in Pulumi identity.
	WhoAmIDetails(ctx context.Context) (WhoAmIResult, error)
	// ChangeStackSecretsProvider edits the secrets provider for the given stack.
	ChangeStackSecretsProvider(
		ctx context.Context, stackName, newSecretsProvider string, opts *ChangeSecretsProviderOptions,
	) error
	// Stack returns a summary of the currently selected stack, if any.
	Stack(context.Context) (*StackSummary, error)
	// CreateStack creates and sets a new stack with the stack name, failing if one already exists.
	CreateStack(context.Context, string) error
	// SelectStack selects and sets an existing stack matching the stack name, failing if none exists.
	SelectStack(context.Context, string) error
	// RemoveStack deletes the stack and all associated configuration and history.
	RemoveStack(context.Context, string, ...optremove.Option) error
	// ListStacks returns all Stacks created under the current Project.
	// This queries underlying backend and may return stacks not present in the Workspace.
	ListStacks(context.Context) ([]StackSummary, error)
	// InstallPlugin acquires the plugin matching the specified name and version.
	InstallPlugin(context.Context, string, string) error
	// InstallPluginFromServer acquires the plugin matching the specified name and version.
	InstallPluginFromServer(context.Context, string, string, string) error
	// RemovePlugin deletes the plugin matching the specified name and version.
	RemovePlugin(context.Context, string, string) error
	// ListPlugins lists all installed plugins.
	ListPlugins(context.Context) ([]workspace.PluginInfo, error)
	// Program returns the program `pulumi.RunFunc` to be used for Preview/Update if any.
	// If none is specified, the stack will refer to ProjectSettings for this information.
	Program() pulumi.RunFunc
	// SetProgram sets the program associated with the Workspace to the specified `pulumi.RunFunc`.
	SetProgram(pulumi.RunFunc)
	// ExportStack exports the deployment state of the stack matching the given name.
	// This can be combined with ImportStack to edit a stack's state (such as recovery from failed deployments).
	ExportStack(context.Context, string) (apitype.UntypedDeployment, error)
	// ImportStack imports the specified deployment state into a pre-existing stack.
	// This can be combined with ExportStack to edit a stack's state (such as recovery from failed deployments).
	ImportStack(context.Context, string, apitype.UntypedDeployment) error
	// StackOutputs gets the current set of Stack outputs from the last Stack.Up().
	StackOutputs(context.Context, string) (OutputMap, error)
}

Workspace is the execution context containing a single Pulumi project, a program, and multiple stacks. Workspaces are used to manage the execution environment, providing various utilities such as plugin installation, environment configuration ($PULUMI_HOME), and creation, deletion, and listing of Stacks.

func NewLocalWorkspace

func NewLocalWorkspace(ctx context.Context, opts ...LocalWorkspaceOption) (Workspace, error)

NewLocalWorkspace creates and configures a LocalWorkspace. LocalWorkspaceOptions can be used to configure things like the working directory, the program to execute, and to seed the directory with source code from a git repository.

Example
ctx := context.Background()
// WorkDir sets the working directory for the LocalWorkspace. The workspace will look for a default
// project settings file (Pulumi.yaml) in this location for information about the Pulumi program.
wd := WorkDir(filepath.Join("..", "path", "to", "pulumi", "project"))
// PulumiHome customizes the location of $PULUMI_HOME where metadata is stored and plugins are installed.
ph := PulumiHome(filepath.Join("~", ".pulumi"))
// Project provides ProjectSettings to set once the workspace is created.
proj := Project(workspace.Project{
	Name:    tokens.PackageName("myproject"),
	Runtime: workspace.NewProjectRuntimeInfo("go", nil),
	Backend: &workspace.ProjectBackend{
		URL: "https://url.to.custom.saas.backend.com",
	},
})
_, _ = NewLocalWorkspace(ctx, wd, ph, proj)
Output:

Directories

Path Synopsis
Package optdestroy contains functional options to be used with stack destroy operations github.com/sdk/v2/go/x/auto Stack.Destroy(...optdestroy.Option)
Package optdestroy contains functional options to be used with stack destroy operations github.com/sdk/v2/go/x/auto Stack.Destroy(...optdestroy.Option)
Package opthistory contains functional options to be used with stack history operations github.com/sdk/v3/go/x/auto Stack.History(ctx, pageSize, page, ...opthistory.Option)
Package opthistory contains functional options to be used with stack history operations github.com/sdk/v3/go/x/auto Stack.History(ctx, pageSize, page, ...opthistory.Option)
Package optpreview contains functional options to be used with stack preview operations github.com/sdk/v2/go/x/auto Stack.Preview(...optpreview.Option)
Package optpreview contains functional options to be used with stack preview operations github.com/sdk/v2/go/x/auto Stack.Preview(...optpreview.Option)
Package optrefresh contains functional options to be used with stack refresh operations github.com/sdk/v2/go/x/auto Stack.Refresh(...optrefresh.Option)
Package optrefresh contains functional options to be used with stack refresh operations github.com/sdk/v2/go/x/auto Stack.Refresh(...optrefresh.Option)
Package optremotedestroy contains functional options to be used with remote stack destroy operations github.com/sdk/v3/go/auto RemoteStack.Destroy(...optremotedestroy.Option)
Package optremotedestroy contains functional options to be used with remote stack destroy operations github.com/sdk/v3/go/auto RemoteStack.Destroy(...optremotedestroy.Option)
Package optremotepreview contains functional options to be used with remote stack preview operations github.com/sdk/v3/go/auto RemoteStack.Preview(...optremotepreview.Option)
Package optremotepreview contains functional options to be used with remote stack preview operations github.com/sdk/v3/go/auto RemoteStack.Preview(...optremotepreview.Option)
Package optremoterefresh contains functional options to be used with remote stack refresh operations github.com/sdk/v3/go/auto RemoteStack.Refresh(...optremoterefresh.Option)
Package optremoterefresh contains functional options to be used with remote stack refresh operations github.com/sdk/v3/go/auto RemoteStack.Refresh(...optremoterefresh.Option)
Package optremoteup contains functional options to be used with remote stack updates github.com/sdk/v3/go/auto RemoteStack.Up(...optremoteup.Option)
Package optremoteup contains functional options to be used with remote stack updates github.com/sdk/v3/go/auto RemoteStack.Up(...optremoteup.Option)
Package optremove contains functional options to be used with workspace stack remove operations github.com/sdk/v2/go/x/auto workspace.RemoveStack(stackName, ...optremove.Option)
Package optremove contains functional options to be used with workspace stack remove operations github.com/sdk/v2/go/x/auto workspace.RemoveStack(stackName, ...optremove.Option)
Package optup contains functional options to be used with stack updates github.com/sdk/v2/go/x/auto Stack.Up(...optup.Option)
Package optup contains functional options to be used with stack updates github.com/sdk/v2/go/x/auto Stack.Up(...optup.Option)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL