• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

auto package - github.com/pulumi/pulumi/sdk/v3/go/auto - Go Packages

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:


开源软件地址:


开源编程语言:


开源软件介绍:

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 filestate 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

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, local 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 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 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 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
	// [email protected]: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
	// [email protected]: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
}

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:         "[email protected]: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:         "[email protected]: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: &am 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap