workspace

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package workspace is a model for Terraform workspaces

Index

Examples

Constants

View Source
const (
	DefaultInstanceName = "instance"
)

DefaultInstanceName is the default name of an instance of a particular module.

Variables

This section is empty.

Functions

This section is empty.

Types

type CannotReadVersionError added in v0.22.0

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

func (CannotReadVersionError) Error added in v0.22.0

func (s CannotReadVersionError) Error() string

type ModuleDefinition

type ModuleDefinition struct {
	Name        string
	Definition  string
	Definitions map[string]string
}

ModuleDefinition represents a module in a Terraform workspace.

func (*ModuleDefinition) Inputs

func (module *ModuleDefinition) Inputs() ([]string, error)

Inputs gets the input parameter names for the module.

func (*ModuleDefinition) Outputs

func (module *ModuleDefinition) Outputs() ([]string, error)

Outputs gets the output parameter names for the module.

func (*ModuleDefinition) Validate

func (module *ModuleDefinition) Validate() (errs *validation.FieldError)

Validate checks the validity of the ModuleDefinition struct.

type ModuleInstance

type ModuleInstance struct {
	ModuleName    string         `json:"module_name"`
	InstanceName  string         `json:"instance_name"`
	Configuration map[string]any `json:"configuration"`
}

ModuleInstance represents the configuration of a single instance of a module.

func (*ModuleInstance) MarshalDefinition

func (instance *ModuleInstance) MarshalDefinition(outputs []string) (json.RawMessage, error)

MarshalDefinition converts the module instance definition into a JSON definition that can be fed to Terraform to be created/destroyed.

Example
instance := ModuleInstance{
	ModuleName:    "foo-module",
	InstanceName:  "instance",
	Configuration: map[string]any{"foo": "bar"},
}

outputs := []string{"output1", "output2"}

defnJSON, err := instance.MarshalDefinition(outputs)
fmt.Println(err)
fmt.Printf("%s\n", string(defnJSON))
Output:

<nil>
{"module":{"instance":{"foo":"bar","source":"./foo-module"}},"output":{"output1":{"sensitive":true,"value":"${module.instance.output1}"},"output2":{"sensitive":true,"value":"${module.instance.output2}"}}}
Example (EmptyOutputs)
instance := ModuleInstance{
	ModuleName:    "foo-module",
	InstanceName:  "instance",
	Configuration: map[string]any{"foo": "bar"},
}

defnJSON, err := instance.MarshalDefinition([]string{})
fmt.Println(err)
fmt.Printf("%s\n", string(defnJSON))
Output:

<nil>
{"module":{"instance":{"foo":"bar","source":"./foo-module"}}}

type ParameterMapping

type ParameterMapping struct {
	TfVariable    string `yaml:"tf_variable"`
	ParameterName string `yaml:"parameter_name"`
}

ParameterMapping mapping for tf variable to service parameter

type TerraformWorkspace

type TerraformWorkspace struct {
	Modules   []ModuleDefinition `json:"modules"`
	Instances []ModuleInstance   `json:"instances"`
	State     []byte             `json:"tfstate"`

	Transformer TfTransformer `json:"transform"`
	// contains filtered or unexported fields
}

TerraformWorkspace represents the directory layout of a Terraform execution. The structure is strict, consisting of several Terraform modules and instances of those modules. The strictness is artificial, but maintains a clear separation between data and code.

It manages the directory structure needed for the commands, serializing and deserializing Terraform state, and all the flags necessary to call Terraform.

All public functions that shell out to Terraform maintain the following invariants: - The function blocks if another terraform shell is running. - The function updates the tfstate once finished. - The function creates and destroys its own dir.

func DeserializeWorkspace

func DeserializeWorkspace(definition []byte) (*TerraformWorkspace, error)

DeserializeWorkspace creates a new TerraformWorkspace from a given JSON serialization of one.

func NewWorkspace

func NewWorkspace(templateVars map[string]any,
	terraformTemplate string,
	terraformTemplates map[string]string,
	importParameterMappings []ParameterMapping,
	parametersToRemove []string,
	parametersToAdd []ParameterMapping) (*TerraformWorkspace, error)

NewWorkspace creates a new TerraformWorkspace from a given template and variables to populate an instance of it. The created instance will have the name specified by the DefaultInstanceName constant.

func (*TerraformWorkspace) Execute

func (workspace *TerraformWorkspace) Execute(ctx context.Context, terraformExecutor executor.TerraformExecutor, commands ...command.TerraformCommand) (executor.ExecutionOutput, error)

func (*TerraformWorkspace) HasState

func (workspace *TerraformWorkspace) HasState() bool

func (*TerraformWorkspace) ModuleDefinitions

func (workspace *TerraformWorkspace) ModuleDefinitions() []ModuleDefinition

func (*TerraformWorkspace) ModuleInstances

func (workspace *TerraformWorkspace) ModuleInstances() []ModuleInstance

func (*TerraformWorkspace) Outputs

func (workspace *TerraformWorkspace) Outputs(_ string) (map[string]any, error)

Outputs gets the Terraform outputs from the state for the instance with the given name. This function DOES NOT invoke Terraform and instead uses the stored state. If no instance exists with the given name, it could be that Terraform pruned it due to having no contents so a blank map is returned.

func (*TerraformWorkspace) RemovePreventDestroy added in v0.11.0

func (workspace *TerraformWorkspace) RemovePreventDestroy() error

func (*TerraformWorkspace) Serialize

func (workspace *TerraformWorkspace) Serialize() (string, error)

Serialize converts the TerraformWorkspace into a JSON string.

func (*TerraformWorkspace) StateTFVersion added in v0.11.0

func (workspace *TerraformWorkspace) StateTFVersion() (*version.Version, error)

func (*TerraformWorkspace) String

func (workspace *TerraformWorkspace) String() string

String returns a human-friendly representation of the workspace suitable for printing to the console.

func (*TerraformWorkspace) UpdateInstanceConfiguration

func (workspace *TerraformWorkspace) UpdateInstanceConfiguration(templateVars map[string]any) error

type TfTransformer

type TfTransformer struct {
	ParameterMappings  []ParameterMapping `json:"parameter_mappings"`
	ParametersToRemove []string           `json:"parameters_to_remove"`
	ParametersToAdd    []ParameterMapping `json:"parameters_to_add"`
}

TfTransformer terraform transformation

func (*TfTransformer) AddParametersInTf

func (ttf *TfTransformer) AddParametersInTf(tf string) string

func (*TfTransformer) CleanTf

func (ttf *TfTransformer) CleanTf(tf string) string

CleanTf removes ttf.ParametersToRemove from tf string

func (*TfTransformer) ReplaceParametersInTf

func (ttf *TfTransformer) ReplaceParametersInTf(tf string) (string, map[string]string, error)

ReplaceParametersInTf replaces ttf.ParameterMappings in tf

type Tfstate

type Tfstate struct {
	Version          int    `json:"version"`
	TerraformVersion string `json:"terraform_version"`
	Outputs          map[string]struct {
		Type  string `json:"type"`
		Value any    `json:"value"`
	} `json:"outputs"`
}

Tfstate is a struct that can help us deserialize the tfstate JSON file.

func NewTfstate

func NewTfstate(stateFile []byte) (*Tfstate, error)

NewTfstate deserializes a tfstate file.

Example (BadVersion)
state := `{
    "version": 5,
    "terraform_version": "1.6.0",
    "serial": 2,
    "outputs": {
        "hostname": {
          "value": "brokertemplate.instance.hostname",
          "type": "string"
        }
    },
    "resources": [
        {
          "module": "module.instance",
          "mode": "managed",
          "type": "google_sql_database",
          "name": "database",
          "provider": "provider.google",
          "instances": []
        }
    ]
  }`

_, err := NewTfstate([]byte(state))
fmt.Printf("%v", err)
Output:

unsupported tfstate version: 5
Example (Good)
state := `{
    "version": 4,
    "terraform_version": "1.6.0",
    "serial": 2,
    "outputs": {
        "hostname": {
          "value": "brokertemplate.instance.hostname",
          "type": "string"
        }
    },
    "resources": [
        {
          "module": "module.instance",
          "mode": "managed",
          "type": "google_sql_database",
          "name": "database",
          "provider": "provider.google",
          "instances": []
        },
        {
          "module": "module.instance",
          "mode": "managed",
          "type": "google_sql_database_instance",
          "name": "instance",
          "provider": "provider.google",
          "instances": []
        }
    ]
  }`

_, err := NewTfstate([]byte(state))
fmt.Printf("%v", err)
Output:

<nil>

func (*Tfstate) GetOutputs

func (module *Tfstate) GetOutputs() map[string]any

GetOutputs gets the key/value outputs defined for a module.

Example
state := `{
    "version": 4,
    "terraform_version": "1.6.0",
    "serial": 2,
    "outputs": {
        "hostname": {
          "value": "somehost",
          "type": "string"
        }
    },
    "resources": [
        {
          "module": "module.instance",
          "mode": "managed",
          "type": "google_sql_database",
          "name": "database",
          "provider": "provider.google",
          "instances": []
        }
    ]
  }`

tfstate, _ := NewTfstate([]byte(state))
fmt.Printf("%v\n", tfstate.GetOutputs())
Output:

map[hostname:somehost]

type Workspace

type Workspace interface {
	Serialize() (string, error)
	HasState() bool

	StateTFVersion() (*version.Version, error)
	Outputs(instance string) (map[string]any, error)
	ModuleDefinitions() []ModuleDefinition
	ModuleInstances() []ModuleInstance
	UpdateInstanceConfiguration(vars map[string]any) error
	Execute(ctx context.Context, executor executor.TerraformExecutor, commands ...command.TerraformCommand) (executor.ExecutionOutput, error)
}

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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