provider

package module
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2022 License: Apache-2.0 Imports: 18 Imported by: 121

README

pulumi-go-provider

Go Reference Go Report Card

A framework for building Go Providers for Pulumi

Note: This library is in active development, and not everthing is hooked up. You should expect breaking changes as we fine tune the exposed APIs. We definitely appreciate community feedback, but you should probably wait to port any existing providers over.

The "Hello, Pulumi" Provider

Here we provide the code to create an entire native provider consumable from any of the Pulumi languages (TypeScript, Python, Go, C#, Java and Pulumi YAML). The binary generated from this file has the capability to serve the provider as well as run schema generation.

package main

import (
	"fmt"

	"github.com/blang/semver"
	p "github.com/pulumi/pulumi-go-provider"
	r "github.com/pulumi/pulumi-go-provider/resource"
)

func main() {
	// Here we list the facilities that the provider will support.
	p.Run("hello", semver.Version{Minor: 1},
		// This provider only supports a single custom resource, so this section is brief.
		p.Resources(&HelloWorld{}))
}

// This is how we define a custom resource.
type HelloWorld struct {
	// Fields that have a `pulumi` tag are used by the provider framework. Fields marked
	// `optional` are optional, so they should have a pointer ahead of their type.
	Name *string `pulumi:"name,optional"`
	// Fields with `provider:"output" are outputs in the Pulumi type system, otherwise
	// they are inputs.`
	Phrase string `pulumi:"phrase" provider:"output"`
}

// The r.Custom interface is what defines the base of a custom resource. It has 2 methods,
// Create and Delete. Create is called to create a new resource.
func (r *HelloWorld) Create(ctx r.Context, name string, preview bool) (r.ID, error) {
	// We indicate we will not know the output of r.Phrase during preview.
	ctx.MarkComputed(&r.Phrase)
	n := name
	// Inputs are already on the struct when Create is called.
	if r.Name != nil {
		n = *r.Name
	}

	// And we add outputs by assigning them to the their fields before we return.
	r.Phrase = fmt.Sprintf("Hello, %s!", n)

	// name is the name component of the resource URN. We pass that as the ID here, but we
	// should append randomness to it later.
	return name, nil
}

// We don't need to do anything to delete this resource, but this is where we would do it.
func (r *HelloWorld) Delete(ctx r.Context, id r.ID) error {
	return nil
}

The framework is doing a lot of work for us here. Since we didn't implement Diff it is assumed to be structural. The diff will require a replace if any field changes, since we didn't implement update. Check will always pass and Read will always fail as unimplemented. All of these methods are available as interfaces in the resource module, and implementing them will replace the default behavior.

Translating Go into the Pulumi type system

The goal of the library is to allow you to write idiomatic Go as much as possible. To that end, your Go code is translated into the Pulumi type system automatically. Here are some useful rules:

  • Tokens are generated directly from type names. A resource defined with the struct Bar in the foo module will get assigned the token ${pkg}:foo:Bar.
  • Custom resources don't interact with Pulumi Input/Output types. They should have raw types and must manually manage dealing with nil values.
  • Component resources do deal with Pulumi Input/Output types. They should only have raw fields when the types are plain.
Struct tags

This library determines how to serialize Go types via struct tags. It uses 2 namespaces: pulumi and provider. Under the pulumi namespace, we support the following tags:

  • name - Name is the fist tag in the after pulumi:. It is required for any field used by the provider. For example pulumi:"foo" tags a field with the name foo.
  • optional - Marking a field as optional in the Pulumi type system. To mark foo as an optional field, we would write: pulumi:"foo,optional".

The rest of the supported tags are under the provider namespace:

  • output - Marks a field as an output instead of an input.
  • secret - Marks a field as secret. This will effect schema generation, but not the internal behavior of the resource.
  • replaceOnChanges - Marks the resource as needing a replace whenever the field changes.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigMissingKeys added in v0.5.0

func ConfigMissingKeys(missing map[string]string) error

Provide a structured error for missing provider keys.

func RunProvider added in v0.4.0

func RunProvider(name string, version semver.Version, provider Provider) error

Types

type CheckFailure added in v0.4.0

type CheckFailure struct {
	Property string
	Reason   string
}

type CheckRequest added in v0.4.0

type CheckRequest struct {
	Urn  presource.URN
	Olds presource.PropertyMap
	News presource.PropertyMap
}

type CheckResponse added in v0.4.0

type CheckResponse struct {
	Inputs   presource.PropertyMap
	Failures []CheckFailure
}

type ConfigureRequest added in v0.4.0

type ConfigureRequest struct {
	Variables map[string]string
	Args      presource.PropertyMap
}

type Context added in v0.4.0

type Context interface {
	context.Context
	// Log logs a global message, including errors and warnings.
	Log(severity diag.Severity, msg string)
	// Logf logs a global message, including errors and warnings.
	Logf(severity diag.Severity, msg string, args ...any)
	// LogStatus logs a global status message, including errors and warnings. Status messages will
	// appear in the `Info` column of the progress display, but not in the final output.
	LogStatus(severity diag.Severity, msg string)
	// LogStatusf logs a global status message, including errors and warnings. Status messages will
	// appear in the `Info` column of the progress display, but not in the final output.
	LogStatusf(severity diag.Severity, msg string, args ...any)
	RuntimeInformation() RunInfo
}

func CtxWithCancel added in v0.5.0

func CtxWithCancel(ctx Context) (Context, context.CancelFunc)

func CtxWithTimeout added in v0.5.0

func CtxWithTimeout(ctx Context, timeout time.Duration) (Context, context.CancelFunc)

func CtxWithValue added in v0.4.0

func CtxWithValue(ctx Context, key, value any) Context

Add a value to a Context. This is the moral equivalent to context.WithValue from the Go standard library.

type CreateRequest added in v0.4.0

type CreateRequest struct {
	Urn        presource.URN         // the Pulumi URN for this resource.
	Properties presource.PropertyMap // the provider inputs to set during creation.
	Timeout    float64               // the create request timeout represented in seconds.
	Preview    bool                  // true if this is a preview and the provider should not actually create the resource.
}

type CreateResponse added in v0.4.0

type CreateResponse struct {
	ID         string                // the ID of the created resource.
	Properties presource.PropertyMap // any properties that were computed during creation.
}

type DeleteRequest added in v0.4.0

type DeleteRequest struct {
	ID         string                // the ID of the resource to delete.
	Urn        presource.URN         // the Pulumi URN for this resource.
	Properties presource.PropertyMap // the current properties on the resource.
	Timeout    float64               // the delete request timeout represented in seconds.
}

type DiffKind added in v0.4.0

type DiffKind string
const (
	Add           DiffKind = "add"            // this property was added
	AddReplace    DiffKind = "add&replace"    // this property was added, and this change requires a replace
	Delete        DiffKind = "delete"         // this property was removed
	DeleteReplace DiffKind = "delete&replace" // this property was removed, and this change requires a replace
	Update        DiffKind = "update"         // this property's value was changed
	UpdateReplace DiffKind = "update&replace" // this property's value was changed, and this change requires a replace
	Stable        DiffKind = "stable"         // this property's value will not change
)

type DiffRequest added in v0.4.0

type DiffRequest struct {
	ID            string
	Urn           presource.URN
	Olds          presource.PropertyMap
	News          presource.PropertyMap
	IgnoreChanges []presource.PropertyKey
}

type DiffResponse added in v0.4.0

type DiffResponse struct {
	DeleteBeforeReplace bool // if true, this resource must be deleted before replacing it.
	HasChanges          bool // if true, this diff represents an actual difference and thus requires an update.
	// detailedDiff is an optional field that contains map from each changed property to the type of the change.
	//
	// The keys of this map are property paths. These paths are essentially Javascript property access expressions
	// in which all elements are literals, and obey the following EBNF-ish grammar:
	//
	//   propertyName := [a-zA-Z_$] { [a-zA-Z0-9_$] }
	//   quotedPropertyName := '"' ( '\' '"' | [^"] ) { ( '\' '"' | [^"] ) } '"'
	//   arrayIndex := { [0-9] }
	//
	//   propertyIndex := '[' ( quotedPropertyName | arrayIndex ) ']'
	//   rootProperty := ( propertyName | propertyIndex )
	//   propertyAccessor := ( ( '.' propertyName ) |  propertyIndex )
	//   path := rootProperty { propertyAccessor }
	//
	// Examples of valid keys:
	// - root
	// - root.nested
	// - root["nested"]
	// - root.double.nest
	// - root["double"].nest
	// - root["double"]["nest"]
	// - root.array[0]
	// - root.array[100]
	// - root.array[0].nested
	// - root.array[0][1].nested
	// - root.nested.array[0].double[1]
	// - root["key with \"escaped\" quotes"]
	// - root["key with a ."]
	// - ["root key with \"escaped\" quotes"].nested
	// - ["root key with a ."][100]
	DetailedDiff map[string]PropertyDiff
}

type GetSchemaRequest added in v0.4.0

type GetSchemaRequest struct {
	Version int
}

type GetSchemaResponse added in v0.4.0

type GetSchemaResponse struct {
	Schema string
}

type InvokeRequest added in v0.4.0

type InvokeRequest struct {
	Token tokens.Type           // the function token to invoke.
	Args  presource.PropertyMap // the arguments for the function invocation.
}

type InvokeResponse added in v0.4.0

type InvokeResponse struct {
	Return   presource.PropertyMap // the returned values, if invoke was successful.
	Failures []CheckFailure        // the failures if any arguments didn't pass verification.
}

type PropertyDiff added in v0.4.0

type PropertyDiff struct {
	Kind      DiffKind // The kind of diff asdsociated with this property.
	InputDiff bool     // The difference is between old and new inputs, not old and new state.
}

type Provider added in v0.4.0

type Provider interface {

	// GetSchema fetches the schema for this resource provider.
	GetSchema(Context, GetSchemaRequest) (GetSchemaResponse, error)
	// Cancel signals the provider to gracefully shut down and abort any ongoing resource operations.
	// Operations aborted in this way will return an error (e.g., `Update` and `Create` will either return a
	// creation error or an initialization error). Since Cancel is advisory and non-blocking, it is up
	// to the host to decide how long to wait after Cancel is called before (e.g.)
	// hard-closing any gRPC connection.
	Cancel(Context) error

	// Provider Config
	CheckConfig(Context, CheckRequest) (CheckResponse, error)
	DiffConfig(Context, DiffRequest) (DiffResponse, error)
	// NOTE: We opt into all options.
	Configure(Context, ConfigureRequest) error

	// Invokes
	Invoke(Context, InvokeRequest) (InvokeResponse, error)

	// Check validates that the given property bag is valid for a resource of the given type and returns the inputs
	// that should be passed to successive calls to Diff, Create, or Update for this resource. As a rule, the provider
	// inputs returned by a call to Check should preserve the original representation of the properties as present in
	// the program inputs. Though this rule is not required for correctness, violations thereof can negatively impact
	// the end-user experience, as the provider inputs are using for detecting and rendering diffs.
	Check(Context, CheckRequest) (CheckResponse, error)
	Diff(Context, DiffRequest) (DiffResponse, error)
	Create(Context, CreateRequest) (CreateResponse, error)
	Read(Context, ReadRequest) (ReadResponse, error)
	Update(Context, UpdateRequest) (UpdateResponse, error)
	Delete(Context, DeleteRequest) error

	// Components Resources
	Construct(pctx Context, typ string, name string,
		ctx *pulumi.Context, inputs comProvider.ConstructInputs, opts pulumi.ResourceOption) (pulumi.ComponentResource, error)
}

type ReadRequest added in v0.4.0

type ReadRequest struct {
	ID         string                // the ID of the resource to read.
	Urn        presource.URN         // the Pulumi URN for this resource.
	Properties presource.PropertyMap // the current state (sufficiently complete to identify the resource).
	Inputs     presource.PropertyMap // the current inputs, if any (only populated during refresh).
}

type ReadResponse added in v0.4.0

type ReadResponse struct {
	ID         string                // the ID of the resource read back (or empty if missing).
	Properties presource.PropertyMap // the state of the resource read from the live environment.
	Inputs     presource.PropertyMap // the inputs for this resource that would be returned from Check.
}

type RunInfo added in v0.4.0

type RunInfo struct {
	PackageName string
	Version     string
}

type UpdateRequest added in v0.4.0

type UpdateRequest struct {
	ID            string                  // the ID of the resource to update.
	Urn           presource.URN           // the Pulumi URN for this resource.
	Olds          presource.PropertyMap   // the old values of provider inputs for the resource to update.
	News          presource.PropertyMap   // the new values of provider inputs for the resource to update.
	Timeout       float64                 // the update request timeout represented in seconds.
	IgnoreChanges []presource.PropertyKey // a set of property paths that should be treated as unchanged.
	Preview       bool                    // true if the provider should not actually create the resource.
}

type UpdateResponse added in v0.4.0

type UpdateResponse struct {
	Properties presource.PropertyMap // any properties that were computed during updating.
}

Directories

Path Synopsis
examples
credentials Module
dna-store Module
file Module
random-login Module
str Module
tests Module
integration module
internal
cancel
Cancel ensures that contexts are canceled when their associated tasks are completed.
Cancel ensures that contexts are canceled when their associated tasks are completed.
context
Context allows systemic wrapping of provider.Context before invoking a subsidiary provider.
Context allows systemic wrapping of provider.Context before invoking a subsidiary provider.
tests module

Jump to

Keyboard shortcuts

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