otf

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2021 License: MPL-2.0 Imports: 23 Imported by: 0

README

oTF

An open source alternative to terraform enterprise.

Functionality is currently limited:

  • Remote execution mode (plans and applies run remotely)
  • State backend (state stored on disk)
  • Workspace management (supports terraform workspace commands)
  • No web frontend; CLI/API support only.

Getting Started

These steps will get you started with running everything on your local system. You'll setup the server, configure SSL so that terraform trusts the server, and then configure terraform. You'll then be able to run terraform commands using the server as a remote backend.

demo

  1. Download a release. The zip file contains two binaries: a daemon and a client, otfd and otf. Extract them to a directory in your PATH, e.g. /usr/local/bin.

  2. Generate SSL cert and key. For example, to generate a self-signed cert and key for localhost using openssl:

    openssl req -x509 -newkey rsa:4096 -sha256 -keyout key.pem -out cert.crt -days 365 -nodes -subj '/CN=localhost' -addext 'subjectAltName=DNS:localhost'
    
  3. Ensure your system trusts the generated cert. For example, on Linux:

    sudo cp cert.crt /usr/local/share/ca-certificates
    sudo update-ca-certificates
    
  4. Ensure you have access to a postgresql server. oTF assumes it's running locally on a unix domain socket in /var/run/postgresql. Create a database named otf:

    createdb otfd
    
  5. Run the oTF daemon:

    otfd --ssl --cert-file=cert.crt --key-file=key.pem
    

    The daemon runs in the foreground and can be left to run.

    Note: you can customise the postgres connection string by passing it via the flag --database.

  6. In another terminal, login to your OTF server (this merely adds some dummy credentials to ~/.terraform.d/credentials.tfrc.json):

    otf login
    
  7. Create an organization:

    otf organizations new mycorp --email=sysadmin@mycorp.co
    
  8. Configure the terraform backend and define a resource:

    cat > main.tf <<EOF
    terraform {
      backend "remote" {
        hostname = "localhost:8080"
        organization = "mycorp"
    
        workspaces {
          name = "dev"
        }
      }
    }
    
    resource "null_resource" "e2e" {}
    EOF
    
  9. Run terraform!:

    terraform init
    terraform plan
    terraform apply
    

Next Steps

oTF is a mere prototype but a roadmap of further features is planned:

  • User AuthN/Z
  • Agents
  • Terminal application
  • Github integration
  • Policies (OPA?)
  • Web frontend

Building

You'll need Go installed.

Clone the repo, and then build and install the binary using the make task:

git clone https://github.com/leg100/otf
cd otf
make install

That'll create a binary inside your go bins directory (defaults to $HOME/go/bin).

Documentation

Overview

Package otf is responsible for domain logic.

Index

Constants

View Source
const (
	DefaultPageNumber = 1
	DefaultPageSize   = 20
	MaxPageSize       = 100

	DefaultUserID   = "user-123"
	DefaultUsername = "otf"

	// ChunkMaxLimit is maximum permissible size of a chunk
	ChunkMaxLimit = 65536

	// ChunkStartMarker is the special byte that prefixes the first chunk
	ChunkStartMarker = byte(2)

	// ChunkEndMarker is the special byte that suffixes the last chunk
	ChunkEndMarker = byte(3)
)
View Source
const (
	DefaultAllowDestroyPlan    = true
	DefaultFileTriggersEnabled = true
	DefaultTerraformVersion    = "0.15.4"
	DefaultExecutionMode       = "remote"
)

Variables

View Source
var (
	// ErrUnauthorized is returned when a receiving a 401.
	ErrUnauthorized = errors.New("unauthorized")

	// ErrResourceNotFound is returned when a receiving a 404.
	ErrResourceNotFound = errors.New("resource not found")

	// ErrRequiredName is returned when a name option is not present.
	ErrRequiredName = errors.New("name is required")

	// ErrInvalidName is returned when the name option has invalid value.
	ErrInvalidName = errors.New("invalid value for name")
)

Generic errors applicable to all resources.

View Source
var (
	// ErrInvalidTerraformVersion is returned when a terraform version string is
	// not a semantic version string (major.minor.patch).
	ErrInvalidTerraformVersion = errors.New("invalid terraform version")

	// ErrWorkspaceLocked is returned when trying to lock a locked workspace.
	ErrWorkspaceLocked = errors.New("workspace already locked")

	// ErrWorkspaceNotLocked is returned when trying to unlock
	// a unlocked workspace.
	ErrWorkspaceNotLocked = errors.New("workspace already unlocked")

	// ErrInvalidWorkspaceID is returned when the workspace ID is invalid.
	ErrInvalidWorkspaceID = errors.New("invalid value for workspace ID")

	// ErrInvalidWorkspaceValue is returned when workspace value is invalid.
	ErrInvalidWorkspaceValue = errors.New("invalid value for workspace")

	// ErrInvalidOrg is returned when the organization option has an invalid value.
	ErrInvalidOrg = errors.New("invalid value for organization")
)

Resource Errors

View Source
var (
	DefaultSessionTimeout          = 20160
	DefaultSessionExpiration       = 20160
	DefaultOrganizationPermissions = OrganizationPermissions{
		CanCreateWorkspace: true,
		CanUpdate:          true,
		CanDestroy:         true,
	}
)
View Source
var (
	ErrRunDiscardNotAllowed     = errors.New("run was not paused for confirmation or priority; discard not allowed")
	ErrRunCancelNotAllowed      = errors.New("run was not planning or applying; cancel not allowed")
	ErrRunForceCancelNotAllowed = errors.New("run was not planning or applying, has not been canceled non-forcefully, or the cool-off period has not yet passed")

	ErrInvalidRunGetOptions = errors.New("invalid run get options")

	// ActiveRunStatuses are those run statuses that deem a run to be active.
	// There can only be at most one active run for a workspace.
	ActiveRunStatuses = []RunStatus{
		RunApplyQueued,
		RunApplying,
		RunConfirmed,
		RunPlanQueued,
		RunPlanned,
		RunPlanning,
	}
)
View Source
var (
	Version = "unknown"
	Commit  = "unknown"
)
View Source
var (
	ErrWorkspaceAlreadyLocked    = errors.New("workspace already locked")
	ErrWorkspaceAlreadyUnlocked  = errors.New("workspace already unlocked")
	ErrInvalidWorkspaceSpecifier = errors.New("invalid workspace specifier options")
)
View Source
var (
	ErrInvalidConfigurationVersionGetOptions = errors.New("invalid configuration version get options")
)
View Source
var (
	ErrInvalidStateVersionGetOptions = errors.New("invalid state version get options")
)

Functions

func GenerateRandomString

func GenerateRandomString(size int) string

GenerateRandomString generates a random string composed of alphanumeric characters of length size.

func GetMapKeys added in v0.0.8

func GetMapKeys(m map[string]interface{}) []string

func Int

func Int(i int) *int

func Int64

func Int64(i int64) *int64

func NewBlobID

func NewBlobID() string

func NewID added in v0.0.8

func NewID(rtype string) string

NewID constructs resource IDs, which are composed of the resource type and a random 16 character string, separated by a hyphen.

func PrefixSlice added in v0.0.8

func PrefixSlice(slice []string, prefix string) (ret []string)

PrefixSlice prefixes each string in a slice with another string.

func SanitizeListOptions

func SanitizeListOptions(opts *ListOptions)

SanitizeListOptions ensures list options adhere to mins and maxs

func String

func String(str string) *string

func TimeNow

func TimeNow() *time.Time

TimeNow is a convenience func to return the pointer of the current time

func UInt

func UInt(i uint) *uint

func Unpack

func Unpack(r io.Reader, dst string) error

Unpack a .tar.gz byte stream to a directory

func UpdateOrganization

func UpdateOrganization(org *Organization, opts *OrganizationUpdateOptions) error

func ValidStringID added in v0.0.8

func ValidStringID(v *string) bool

ValidStringID checks if the given string pointer is non-nil and contains a typical string identifier.

Types

type Apply

type Apply struct {
	ID string `db:"apply_id"`

	Timestamps

	Resources

	Status           ApplyStatus
	StatusTimestamps TimestampMap

	// RunID is the ID of the Run the Apply belongs to.
	RunID string
}

func (*Apply) Do

func (a *Apply) Do(run *Run, env Environment) error

func (*Apply) Finish added in v0.0.8

func (a *Apply) Finish(run *Run) (*Event, error)

Finish updates the run to reflect its apply having finished. An event is returned reflecting the run's new status.

func (*Apply) GetID added in v0.0.8

func (a *Apply) GetID() string

func (*Apply) GetStatus added in v0.0.8

func (a *Apply) GetStatus() string

func (*Apply) Start added in v0.0.8

func (a *Apply) Start(run *Run) error

Start updates the run to reflect its apply having started

func (*Apply) String added in v0.0.8

func (a *Apply) String() string

func (*Apply) UpdateStatus

func (a *Apply) UpdateStatus(status ApplyStatus)

type ApplyService

type ApplyService interface {
	Get(id string) (*Apply, error)

	JobService
}

type ApplyStatus added in v0.0.8

type ApplyStatus string

ApplyStatus represents an apply state.

const (
	ApplyCanceled    ApplyStatus = "canceled"
	ApplyCreated     ApplyStatus = "created"
	ApplyErrored     ApplyStatus = "errored"
	ApplyFinished    ApplyStatus = "finished"
	ApplyPending     ApplyStatus = "pending"
	ApplyQueued      ApplyStatus = "queued"
	ApplyRunning     ApplyStatus = "running"
	ApplyUnreachable ApplyStatus = "unreachable"
)

List all available apply statuses supported in OTF.

type BlobStore

type BlobStore interface {
	// Get fetches a blob
	Get(string) ([]byte, error)

	// Put uploads a blob
	Put(string, []byte) error
}

BlobStore implementations provide a persistent store from and to which binary objects can be fetched and uploaded.

type CSV added in v0.0.8

type CSV []string

func (*CSV) Scan added in v0.0.8

func (c *CSV) Scan(src interface{}) error

func (CSV) Value added in v0.0.8

func (c CSV) Value() (driver.Value, error)

type Change

type Change struct {
	Actions []ChangeAction
}

Change represents the type of change being made

type ChangeAction

type ChangeAction string
const (
	CreateAction ChangeAction = "create"
	UpdateAction ChangeAction = "update"
	DeleteAction ChangeAction = "delete"
)

type ChunkStore added in v0.0.8

type ChunkStore interface {
	// GetChunk fetches a blob chunk
	GetChunk(ctx context.Context, id string, opts GetChunkOptions) ([]byte, error)

	// PutChunk uploads a blob chunk
	PutChunk(ctx context.Context, id string, chunk []byte, opts PutChunkOptions) error
}

ChunkStore implementations provide a persistent store from and to which chunks of binary objects can be fetched and uploaded.

type ConfigurationSource added in v0.0.8

type ConfigurationSource string

ConfigurationSource represents a source of a configuration version.

type ConfigurationStatus added in v0.0.8

type ConfigurationStatus string

ConfigurationStatus represents a configuration version status.

const (
	DefaultAutoQueueRuns       = true
	DefaultConfigurationSource = "tfe-api"

	//List all available configuration version statuses.
	ConfigurationErrored  ConfigurationStatus = "errored"
	ConfigurationPending  ConfigurationStatus = "pending"
	ConfigurationUploaded ConfigurationStatus = "uploaded"
)

type ConfigurationVersion

type ConfigurationVersion struct {
	ID string `db:"configuration_version_id" jsonapi:"primary,configuration-versions"`

	Timestamps

	AutoQueueRuns    bool
	Source           ConfigurationSource
	Speculative      bool
	Status           ConfigurationStatus
	StatusTimestamps TimestampMap

	// Config is a tarball of the uploaded configuration. Note: this is not
	// necessarily populated.
	Config []byte

	// Configuration Version belongs to a Workspace
	Workspace *Workspace `db:"workspaces"`
}

ConfigurationVersion is a representation of an uploaded or ingressed Terraform configuration in A workspace must have at least one configuration version before any runs may be queued on it.

func (*ConfigurationVersion) GetID added in v0.0.8

func (cv *ConfigurationVersion) GetID() string

func (*ConfigurationVersion) String added in v0.0.8

func (cv *ConfigurationVersion) String() string

type ConfigurationVersionCreateOptions added in v0.0.8

type ConfigurationVersionCreateOptions struct {
	// Type is a public field utilized by JSON:API to
	// set the resource type via the field tag.
	// It is not a user-defined value and does not need to be set.
	// https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,configuration-versions"`

	// When true, runs are queued automatically when the configuration version
	// is uploaded.
	AutoQueueRuns *bool `jsonapi:"attr,auto-queue-runs,omitempty"`

	// When true, this configuration version can only be used for planning.
	Speculative *bool `jsonapi:"attr,speculative,omitempty"`
}

ConfigurationVersionCreateOptions represents the options for creating a configuration version.

type ConfigurationVersionFactory

type ConfigurationVersionFactory struct {
	WorkspaceService WorkspaceService
}

ConfigurationVersionFactory creates ConfigurationVersion objects

func (*ConfigurationVersionFactory) NewConfigurationVersion

func (f *ConfigurationVersionFactory) NewConfigurationVersion(workspaceID string, opts ConfigurationVersionCreateOptions) (*ConfigurationVersion, error)

NewConfigurationVersion creates a ConfigurationVersion object from scratch

type ConfigurationVersionGetOptions

type ConfigurationVersionGetOptions struct {
	// ID of config version to retrieve
	ID *string

	// Get latest config version for this workspace ID
	WorkspaceID *string

	// Config toggles whether to retrieve the tarball of config files too.
	Config bool
}

ConfigurationVersionGetOptions are options for retrieving a single config version. Either ID *or* WorkspaceID must be specfiied.

type ConfigurationVersionList

type ConfigurationVersionList struct {
	*Pagination
	Items []*ConfigurationVersion
}

ConfigurationVersionList represents a list of configuration versions.

type ConfigurationVersionListOptions

type ConfigurationVersionListOptions struct {
	// A list of relations to include
	Include *string `schema:"include"`

	ListOptions

	// Filter by run statuses (with an implicit OR condition)
	Statuses []ConfigurationStatus

	// Filter by workspace ID
	WorkspaceID *string
}

ConfigurationVersionListOptions are options for paginating and filtering a list of configuration versions

type ConfigurationVersionService

type ConfigurationVersionService interface {
	Create(workspaceID string, opts ConfigurationVersionCreateOptions) (*ConfigurationVersion, error)
	Get(id string) (*ConfigurationVersion, error)
	GetLatest(workspaceID string) (*ConfigurationVersion, error)
	List(workspaceID string, opts ConfigurationVersionListOptions) (*ConfigurationVersionList, error)
	Upload(id string, payload []byte) error
	Download(id string) ([]byte, error)
}

type Entitlements

type Entitlements struct {
	ID                    string `jsonapi:"primary,entitlement-sets"`
	Agents                bool   `jsonapi:"attr,agents"`
	AuditLogging          bool   `jsonapi:"attr,audit-logging"`
	CostEstimation        bool   `jsonapi:"attr,cost-estimation"`
	Operations            bool   `jsonapi:"attr,operations"`
	PrivateModuleRegistry bool   `jsonapi:"attr,private-module-registry"`
	SSO                   bool   `jsonapi:"attr,sso"`
	Sentinel              bool   `jsonapi:"attr,sentinel"`
	StateStorage          bool   `jsonapi:"attr,state-storage"`
	Teams                 bool   `jsonapi:"attr,teams"`
	VCSIntegrations       bool   `jsonapi:"attr,vcs-integrations"`
}

Entitlements represents the entitlements of an organization. Unlike TFE/TFC, OTF is free and therefore the user is entitled to all currently supported services. Entitlements represents the entitlements of an organization.

func DefaultEntitlements

func DefaultEntitlements(organizationID string) *Entitlements

DefaultEntitlements constructs an Entitlements struct with currently supported entitlements.

type Environment added in v0.0.8

type Environment interface {
	GetPath() string
	GetConfigurationVersionService() ConfigurationVersionService
	GetStateVersionService() StateVersionService
	GetRunService() RunService
	RunCLI(name string, args ...string) error
	RunFunc(fn EnvironmentFunc) error
}

Environment provides a Job with access to various oTF services, a working directory, and the ability to invoke arbitrary commands and go functions. Invoking commands and functions via the environment means the environment can handle canceling them if necessary.

type EnvironmentFunc added in v0.0.8

type EnvironmentFunc func(context.Context, Environment) error

EnvironmentFunc is a go func that is invoked within an environment (and with access to the environment).

type ErrJobAlreadyStarted

type ErrJobAlreadyStarted error

type Event

type Event struct {
	Type    EventType
	Payload interface{}
}

type EventService

type EventService interface {
	Publish(Event)
	Subscribe(id string) (Subscription, error)
}

type EventType

type EventType string
const (
	OrganizationCreated        EventType = "organization_created"
	OrganizationDeleted        EventType = "organization_deleted"
	WorkspaceCreated           EventType = "workspace_created"
	WorkspaceDeleted           EventType = "workspace_deleted"
	RunCreated                 EventType = "run_created"
	RunCompleted               EventType = "run_completed"
	EventRunCanceled           EventType = "run_canceled"
	EventRunApplied            EventType = "run_applied"
	EventRunPlanned            EventType = "run_planned"
	EventRunPlannedAndFinished EventType = "run_planned_and_finished"
	EventPlanQueued            EventType = "plan_queued"
	EventApplyQueued           EventType = "apply_queued"
	EventError                 EventType = "error"
)

type GetChunkOptions

type GetChunkOptions struct {
	// Limit is the size of the chunk to retrieve
	Limit int `schema:"limit"`

	// Offset is the position within the binary object to retrieve the chunk
	Offset int `schema:"offset"`
}

type Job

type Job interface {
	// Do does the piece of work in an execution environment
	Do(*Run, Environment) error

	// GetID gets the ID of the Job
	GetID() string

	// GetStatus gets the status of the Job
	GetStatus() string
}

Job is either a Run's Plan or Apply.

type JobFinishOptions

type JobFinishOptions struct {
	Errored bool
}

type JobSelector added in v0.0.8

type JobSelector struct {
	PlanService  PlanService
	ApplyService ApplyService
}

JobSelector selects the appropriate job and job service for a Run

func (*JobSelector) GetJob added in v0.0.8

func (jsp *JobSelector) GetJob(run *Run) (Job, JobService, error)

GetJob returns the appropriate job and job service for the Run

type JobService

type JobService interface {
	// Start is called by an agent when it starts a job. ErrJobAlreadyStarted
	// should be returned if another agent has already started it.
	Start(ctx context.Context, id string, opts JobStartOptions) (*Run, error)

	// Finish is called by an agent when it finishes a job.
	Finish(ctx context.Context, id string, opts JobFinishOptions) (*Run, error)

	// ChunkStore handles putting and getting chunks of logs
	ChunkStore
}

type JobStartOptions

type JobStartOptions struct {
	AgentID string
}

type JobWriter

type JobWriter struct {
	// ID of Job to write logs on behalf of.
	ID string

	// JobService for uploading logs to server
	JobService

	logr.Logger
	// contains filtered or unexported fields
}

JobWriter writes logs on behalf of a job.

func (*JobWriter) Close

func (w *JobWriter) Close() error

Close must be called to complete writing job logs

func (*JobWriter) Write

func (w *JobWriter) Write(p []byte) (int, error)

Write uploads a chunk of logs to the server.

type ListOptions added in v0.0.8

type ListOptions struct {
	// The page number to request. The results vary based on the PageSize.
	PageNumber int `schema:"page[number],omitempty"`

	// The number of elements returned in a single page.
	PageSize int `schema:"page[size],omitempty"`
}

ListOptions is used to specify pagination options when making API requests. Pagination allows breaking up large result sets into chunks, or "pages".

func (*ListOptions) GetLimit added in v0.0.8

func (o *ListOptions) GetLimit() uint64

GetLimit calculates the limit for use in SQL queries.

func (*ListOptions) GetOffset added in v0.0.8

func (o *ListOptions) GetOffset() uint64

GetOffset calculates the offset for use in SQL queries.

type Organization

type Organization struct {
	ID string `db:"organization_id"`

	Timestamps

	Name            string
	Email           string
	SessionRemember int
	SessionTimeout  int
}

Organization represents a Terraform Enterprise organization.

func NewOrganization

func NewOrganization(opts OrganizationCreateOptions) (*Organization, error)

func (*Organization) GetID added in v0.0.8

func (org *Organization) GetID() string

func (*Organization) String added in v0.0.8

func (org *Organization) String() string

type OrganizationCreateOptions added in v0.0.8

type OrganizationCreateOptions struct {
	// Type is a public field utilized by JSON:API to
	// set the resource type via the field tag.
	// It is not a user-defined value and does not need to be set.
	// https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,organizations"`

	// Name of the organization.
	Name *string `jsonapi:"attr,name"`

	// Admin email address.
	Email *string `jsonapi:"attr,email"`

	SessionRemember *int `jsonapi:"attr,session-remember,omitempty"`

	// Session timeout after inactivity (minutes).
	SessionTimeout *int `jsonapi:"attr,session-timeout,omitempty"`
}

OrganizationCreateOptions represents the options for creating an organization.

func (OrganizationCreateOptions) Valid added in v0.0.8

func (o OrganizationCreateOptions) Valid() error

type OrganizationList

type OrganizationList struct {
	*Pagination
	Items []*Organization
}

OrganizationList represents a list of Organizations.

type OrganizationListOptions added in v0.0.8

type OrganizationListOptions struct {
	ListOptions
}

OrganizationListOptions represents the options for listing organizations.

type OrganizationPermissions added in v0.0.8

type OrganizationPermissions struct {
	CanCreateTeam               bool `json:"can-create-team"`
	CanCreateWorkspace          bool `json:"can-create-workspace"`
	CanCreateWorkspaceMigration bool `json:"can-create-workspace-migration"`
	CanDestroy                  bool `json:"can-destroy"`
	CanTraverse                 bool `json:"can-traverse"`
	CanUpdate                   bool `json:"can-update"`
	CanUpdateAPIToken           bool `json:"can-update-api-token"`
	CanUpdateOAuth              bool `json:"can-update-oauth"`
	CanUpdateSentinel           bool `json:"can-update-sentinel"`
}

OrganizationPermissions represents the organization permissions.

type OrganizationService

type OrganizationService interface {
	Create(ctx context.Context, opts OrganizationCreateOptions) (*Organization, error)
	Get(name string) (*Organization, error)
	List(opts OrganizationListOptions) (*OrganizationList, error)
	Update(name string, opts *OrganizationUpdateOptions) (*Organization, error)
	Delete(name string) error
	GetEntitlements(name string) (*Entitlements, error)
}

type OrganizationStore

type OrganizationStore interface {
	Create(org *Organization) (*Organization, error)
	Get(name string) (*Organization, error)
	List(opts OrganizationListOptions) (*OrganizationList, error)
	Update(name string, fn func(*Organization) error) (*Organization, error)
	Delete(name string) error
}

type OrganizationUpdateOptions added in v0.0.8

type OrganizationUpdateOptions struct {
	// Type is a public field utilized by JSON:API to
	// set the resource type via the field tag.
	// It is not a user-defined value and does not need to be set.
	// https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,organizations"`

	// New name for the organization.
	Name *string `jsonapi:"attr,name,omitempty"`

	// New admin email address.
	Email *string `jsonapi:"attr,email,omitempty"`

	// Session expiration (minutes).
	SessionRemember *int `jsonapi:"attr,session-remember,omitempty"`

	// Session timeout after inactivity (minutes).
	SessionTimeout *int `jsonapi:"attr,session-timeout,omitempty"`
}

OrganizationUpdateOptions represents the options for updating an organization.

type Pagination added in v0.0.8

type Pagination struct {
	CurrentPage  int `json:"current-page"`
	PreviousPage int `json:"prev-page"`
	NextPage     int `json:"next-page"`
	TotalPages   int `json:"total-pages"`
	TotalCount   int `json:"total-count"`
}

Pagination is used to return the pagination details of an API request.

func NewPagination

func NewPagination(opts ListOptions, count int) *Pagination

NewPagination constructs a Pagination obj.

type Plan

type Plan struct {
	ID string `db:"plan_id"`

	Timestamps

	Resources

	Status           PlanStatus
	StatusTimestamps TimestampMap

	// PlanFile is the blob ID of the execution plan file in binary format
	PlanFile []byte

	// PlanJSON is the blob ID of the execution plan file in json format
	PlanJSON []byte

	// RunID is the ID of the Run the Plan belongs to.
	RunID string
}

Plan represents a Terraform Enterprise plan.

func (*Plan) CalculateTotals added in v0.0.8

func (p *Plan) CalculateTotals() error

CalculateTotals produces a summary of planned changes and updates the object with the summary.

func (*Plan) Do

func (p *Plan) Do(run *Run, env Environment) error

func (*Plan) Finish added in v0.0.8

func (p *Plan) Finish(run *Run) (*Event, error)

Finish updates the run to reflect its plan having finished. An event is returned reflecting the run's new status.

func (*Plan) GetID added in v0.0.8

func (p *Plan) GetID() string

func (*Plan) GetStatus added in v0.0.8

func (p *Plan) GetStatus() string

func (*Plan) HasChanges

func (p *Plan) HasChanges() bool

HasChanges determines whether plan has any changes (adds/changes/deletions).

func (*Plan) Start added in v0.0.8

func (p *Plan) Start(run *Run) error

Start updates the plan to reflect its plan having started

func (*Plan) String added in v0.0.8

func (p *Plan) String() string

func (*Plan) UpdateStatus

func (p *Plan) UpdateStatus(status PlanStatus)

type PlanEnqueuer

type PlanEnqueuer interface {
	EnqueuePlan(id string) error
}

type PlanFile

type PlanFile struct {
	ResourcesChanges []ResourceChange `json:"resource_changes"`
}

PlanFile represents the schema of a plan file

func (*PlanFile) Changes

func (pf *PlanFile) Changes() (tally Resources)

Changes provides a tally of the types of changes proposed in the plan file.

type PlanFileOptions added in v0.0.8

type PlanFileOptions struct {
	// Format of plan file. Valid values are json and binary.
	Format string `schema:"format"`
}

PlanFileOptions represents the options for retrieving the plan file for a run.

type PlanService

type PlanService interface {
	Get(id string) (*Plan, error)
	GetPlanJSON(id string) ([]byte, error)

	JobService
}

type PlanStatus added in v0.0.8

type PlanStatus string

PlanStatus represents a plan state.

const (
	LocalStateFilename  = "terraform.tfstate"
	PlanFilename        = "plan.out"
	JSONPlanFilename    = "plan.out.json"
	ApplyOutputFilename = "apply.out"

	//List all available plan statuses.
	PlanCanceled    PlanStatus = "canceled"
	PlanCreated     PlanStatus = "created"
	PlanErrored     PlanStatus = "errored"
	PlanFinished    PlanStatus = "finished"
	PlanMFAWaiting  PlanStatus = "mfa_waiting"
	PlanPending     PlanStatus = "pending"
	PlanQueued      PlanStatus = "queued"
	PlanRunning     PlanStatus = "running"
	PlanUnreachable PlanStatus = "unreachable"
)

type PutChunkOptions

type PutChunkOptions struct {
	// Start indicates this is the first chunk
	Start bool `schema:"start"`

	// End indicates this is the last and final chunk
	End bool `schema:"end"`
}

type Queue

type Queue interface {
	Add(*Run) error
	Remove(*Run) error
}

Queue implementations are able to add and remove runs from a queue-like structure

type ResourceChange

type ResourceChange struct {
	Change Change
}

ResourceChange represents a proposed change to a resource in a plan file

type Resources added in v0.0.8

type Resources struct {
	ResourceAdditions    int `db:"resource_additions"`
	ResourceChanges      int `db:"resource_changes"`
	ResourceDestructions int `db:"resource_destructions"`
}

Resources summaries updates to a workspace's resources, either proposed as part of a plan, or made as a result of an apply.

func ParseApplyOutput added in v0.0.8

func ParseApplyOutput(output string) (Resources, error)

type Run

type Run struct {
	ID string `db:"run_id" jsonapi:"primary,runs"`

	Timestamps

	IsDestroy        bool
	Message          string
	PositionInQueue  int
	Refresh          bool
	RefreshOnly      bool
	Status           RunStatus
	StatusTimestamps TimestampMap
	ReplaceAddrs     CSV
	TargetAddrs      CSV

	// Relations
	Plan                 *Plan                 `db:"plans"`
	Apply                *Apply                `db:"applies"`
	Workspace            *Workspace            `db:"workspaces"`
	ConfigurationVersion *ConfigurationVersion `db:"configuration_versions"`
}

func (*Run) Cancel

func (r *Run) Cancel() error

Cancel run.

func (*Run) Discard

func (r *Run) Discard() error

Discard updates the state of a run to reflect it having been discarded.

func (*Run) Do

func (r *Run) Do(env Environment) error

Do invokes the necessary steps before a plan or apply can proceed.

func (*Run) ForceCancel

func (r *Run) ForceCancel() error

ForceCancel updates the state of a run to reflect it having been forcefully cancelled.

func (*Run) ForceCancelAvailableAt

func (r *Run) ForceCancelAvailableAt() time.Time

func (*Run) GetID

func (r *Run) GetID() string

func (*Run) GetStatus

func (r *Run) GetStatus() string

func (*Run) IsActive

func (r *Run) IsActive() bool

IsActive determines whether run is currently the active run on a workspace, i.e. it is neither finished nor pending

func (*Run) IsCancelable

func (r *Run) IsCancelable() bool

IsCancelable determines whether run can be cancelled.

func (*Run) IsConfirmable

func (r *Run) IsConfirmable() bool

IsConfirmable determines whether run can be confirmed.

func (*Run) IsDiscardable

func (r *Run) IsDiscardable() bool

IsDiscardable determines whether run can be discarded.

func (*Run) IsDone

func (r *Run) IsDone() bool

IsDone determines whether run has reached an end state, e.g. applied, discarded, etc.

func (*Run) IsForceCancelable

func (r *Run) IsForceCancelable() bool

IsForceCancelable determines whether a run can be forcibly cancelled.

func (*Run) IsSpeculative

func (r *Run) IsSpeculative() bool

func (*Run) String added in v0.0.8

func (r *Run) String() string

func (*Run) UpdateStatus

func (r *Run) UpdateStatus(status RunStatus)

UpdateStatus updates the status of the run as well as its plan and apply

type RunApplyOptions added in v0.0.8

type RunApplyOptions struct {
	// An optional comment about the run.
	Comment *string `jsonapi:"attr,comment,omitempty"`
}

RunApplyOptions represents the options for applying a run.

type RunCancelOptions added in v0.0.8

type RunCancelOptions struct {
	// An optional explanation for why the run was canceled.
	Comment *string `jsonapi:"attr,comment,omitempty"`
}

RunCancelOptions represents the options for canceling a run.

type RunCreateOptions added in v0.0.8

type RunCreateOptions struct {
	// Type is a public field utilized by JSON:API to set the resource type via
	// the field tag.  It is not a user-defined value and does not need to be
	// set.  https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,runs"`

	// Specifies if this plan is a destroy plan, which will destroy all
	// provisioned resources.
	IsDestroy *bool `jsonapi:"attr,is-destroy,omitempty"`

	// Refresh determines if the run should
	// update the state prior to checking for differences
	Refresh *bool `jsonapi:"attr,refresh,omitempty"`

	// RefreshOnly determines whether the run should ignore config changes
	// and refresh the state only
	RefreshOnly *bool `jsonapi:"attr,refresh-only,omitempty"`

	// Specifies the message to be associated with this run.
	Message *string `jsonapi:"attr,message,omitempty"`

	// Specifies the configuration version to use for this run. If the
	// configuration version object is omitted, the run will be created using the
	// workspace's latest configuration version.
	ConfigurationVersion *ConfigurationVersion `jsonapi:"relation,configuration-version"`

	// Specifies the workspace where the run will be executed.
	Workspace *Workspace `jsonapi:"relation,workspace"`

	// If non-empty, requests that Terraform should create a plan including
	// actions only for the given objects (specified using resource address
	// syntax) and the objects they depend on.
	//
	// This capability is provided for exceptional circumstances only, such as
	// recovering from mistakes or working around existing Terraform
	// limitations. Terraform will generally mention the -target command line
	// option in its error messages describing situations where setting this
	// argument may be appropriate. This argument should not be used as part
	// of routine workflow and Terraform will emit warnings reminding about
	// this whenever this property is set.
	TargetAddrs []string `jsonapi:"attr,target-addrs,omitempty"`

	// If non-empty, requests that Terraform create a plan that replaces
	// (destroys and then re-creates) the objects specified by the given
	// resource addresses.
	ReplaceAddrs []string `jsonapi:"attr,replace-addrs,omitempty"`
}

RunCreateOptions represents the options for creating a new run.

func (RunCreateOptions) Valid added in v0.0.8

func (o RunCreateOptions) Valid() error

type RunDiscardOptions added in v0.0.8

type RunDiscardOptions struct {
	// An optional explanation for why the run was discarded.
	Comment *string `jsonapi:"attr,comment,omitempty"`
}

RunDiscardOptions represents the options for discarding a run.

type RunFactory

type RunFactory struct {
	ConfigurationVersionService ConfigurationVersionService
	WorkspaceService            WorkspaceService
}

RunFactory is a factory for constructing Run objects.

func (*RunFactory) NewRun

func (f *RunFactory) NewRun(opts RunCreateOptions) (*Run, error)

NewRun constructs a run object.

type RunForceCancelOptions added in v0.0.8

type RunForceCancelOptions struct {
	// An optional comment explaining the reason for the force-cancel.
	Comment *string `jsonapi:"attr,comment,omitempty"`
}

RunForceCancelOptions represents the options for force-canceling a run.

type RunGetOptions

type RunGetOptions struct {
	// ID of run to retrieve
	ID *string

	// Get run via apply ID
	ApplyID *string

	// Get run via plan ID
	PlanID *string

	// IncludePlanFile toggles including the plan file in the retrieved run.
	IncludePlanFile bool

	// IncludePlanFile toggles including the plan file, in JSON format, in the
	// retrieved run.
	IncludePlanJSON bool
}

RunGetOptions are options for retrieving a single Run. Either ID or ApplyID or PlanID must be specfiied.

type RunList

type RunList struct {
	*Pagination
	Items []*Run
}

RunList represents a list of runs.

type RunListOptions

type RunListOptions struct {
	ListOptions

	// A list of relations to include. See available resources:
	// https://www.terraform.io/docs/cloud/api/run.html#available-related-resources
	Include *string `schema:"include"`

	// Filter by run statuses (with an implicit OR condition)
	Statuses []RunStatus

	// Filter by workspace ID
	WorkspaceID *string
}

RunListOptions are options for paginating and filtering a list of runs

type RunPermissions added in v0.0.8

type RunPermissions struct {
	CanApply        bool `json:"can-apply"`
	CanCancel       bool `json:"can-cancel"`
	CanDiscard      bool `json:"can-discard"`
	CanForceCancel  bool `json:"can-force-cancel"`
	CanForceExecute bool `json:"can-force-execute"`
}

RunPermissions represents the run permissions.

type RunService

type RunService interface {
	// Create a new run with the given options.
	Create(ctx context.Context, opts RunCreateOptions) (*Run, error)

	Get(id string) (*Run, error)
	List(opts RunListOptions) (*RunList, error)

	// Apply a run by its ID.
	Apply(id string, opts RunApplyOptions) error

	Discard(id string, opts RunDiscardOptions) error
	Cancel(id string, opts RunCancelOptions) error
	ForceCancel(id string, opts RunForceCancelOptions) error
	EnqueuePlan(id string) error

	GetPlanFile(ctx context.Context, runID string, opts PlanFileOptions) ([]byte, error)
	UploadPlanFile(ctx context.Context, runID string, plan []byte, opts PlanFileOptions) error
}

RunService implementations allow interactions with runs

type RunStatus added in v0.0.8

type RunStatus string

RunStatus represents a run state.

const (
	// DefaultRefresh specifies that the state be refreshed prior to running a
	// plan
	DefaultRefresh = true

	// List all available run statuses supported in OTF.
	RunApplied            RunStatus = "applied"
	RunApplyQueued        RunStatus = "apply_queued"
	RunApplying           RunStatus = "applying"
	RunCanceled           RunStatus = "canceled"
	RunForceCanceled      RunStatus = "force_canceled"
	RunConfirmed          RunStatus = "confirmed"
	RunDiscarded          RunStatus = "discarded"
	RunErrored            RunStatus = "errored"
	RunPending            RunStatus = "pending"
	RunPlanQueued         RunStatus = "plan_queued"
	RunPlanned            RunStatus = "planned"
	RunPlannedAndFinished RunStatus = "planned_and_finished"
	RunPlanning           RunStatus = "planning"

	PlanBinaryFormat = "binary"
	PlanJSONFormat   = "json"
)

type RunStatusTimestamp added in v0.0.8

type RunStatusTimestamp struct {
	Status    RunStatus
	Timestamp time.Time
}

type RunStore

type RunStore interface {
	Create(run *Run) (*Run, error)
	Get(opts RunGetOptions) (*Run, error)
	List(opts RunListOptions) (*RunList, error)
	// TODO: add support for a special error type that tells update to skip
	// updates - useful when fn checks current fields and decides not to update
	Update(opts RunGetOptions, fn func(*Run) error) (*Run, error)
}

RunStore implementations persist Run objects.

type State

type State struct {
	Version int
	Serial  int64
	Lineage string
	Outputs map[string]StateOutput
}

State represents the schema of terraform state.

func Parse

func Parse(data []byte) (*State, error)

Parse unmarshals terraform state from a raw byte slice into a State object.

type StateOutput

type StateOutput struct {
	Value string
	Type  string
}

StateOutput represents an output in terraform state.

type StateVersion

type StateVersion struct {
	ID string `db:"state_version_id"`

	Timestamps

	Serial       int64
	VCSCommitSHA string
	VCSCommitURL string

	// State is state file itself. Note: not always populated.
	State []byte

	// State version belongs to a workspace
	Workspace *Workspace `db:"workspaces"`

	// State version has many outputs
	Outputs []*StateVersionOutput `db:"state_version_outputs"`
}

StateVersion represents a Terraform Enterprise state version.

func (*StateVersion) DownloadURL

func (sv *StateVersion) DownloadURL() string

func (*StateVersion) GetID added in v0.0.8

func (sv *StateVersion) GetID() string

func (*StateVersion) String added in v0.0.8

func (sv *StateVersion) String() string

type StateVersionCreateOptions added in v0.0.8

type StateVersionCreateOptions struct {
	// Type is a public field utilized by JSON:API to
	// set the resource type via the field tag.
	// It is not a user-defined value and does not need to be set.
	// https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,state-versions"`

	// The lineage of the state.
	Lineage *string `jsonapi:"attr,lineage,omitempty"`

	// The MD5 hash of the state version.
	MD5 *string `jsonapi:"attr,md5"`

	// The serial of the state.
	Serial *int64 `jsonapi:"attr,serial"`

	// The base64 encoded state.
	State *string `jsonapi:"attr,state"`

	// Force can be set to skip certain validations. Wrong use
	// of this flag can cause data loss, so USE WITH CAUTION!
	Force *bool `jsonapi:"attr,force"`

	// Specifies the run to associate the state with.
	Run *Run `jsonapi:"relation,run,omitempty"`
}

StateVersionCreateOptions represents the options for creating a state version.

type StateVersionFactory

type StateVersionFactory struct {
	WorkspaceService WorkspaceService
}

func (*StateVersionFactory) NewStateVersion

func (f *StateVersionFactory) NewStateVersion(workspaceID string, opts StateVersionCreateOptions) (*StateVersion, error)

type StateVersionGetOptions

type StateVersionGetOptions struct {
	// ID of state version to retrieve
	ID *string

	// Get current state version belonging to workspace with this ID
	WorkspaceID *string

	// State toggles retrieving the actual state file too.
	State bool
}

StateVersionGetOptions are options for retrieving a single StateVersion. Either ID *or* WorkspaceID must be specfiied.

type StateVersionList

type StateVersionList struct {
	*Pagination
	Items []*StateVersion
}

StateVersionList represents a list of state versions.

type StateVersionListOptions added in v0.0.8

type StateVersionListOptions struct {
	ListOptions
	Organization *string `schema:"filter[organization][name]"`
	Workspace    *string `schema:"filter[workspace][name]"`
}

StateVersionListOptions represents the options for listing state versions.

type StateVersionOutput

type StateVersionOutput struct {
	ID string `db:"state_version_output_id"`

	Timestamps

	Name      string
	Sensitive bool
	Type      string
	Value     string

	// StateVersionOutput belongs to State Version
	StateVersionID string
}

func (*StateVersionOutput) String added in v0.0.8

func (svo *StateVersionOutput) String() string

type StateVersionOutputList

type StateVersionOutputList []*StateVersionOutput

type StateVersionService

type StateVersionService interface {
	Create(workspaceID string, opts StateVersionCreateOptions) (*StateVersion, error)
	Current(workspaceID string) (*StateVersion, error)
	Get(id string) (*StateVersion, error)
	Download(id string) ([]byte, error)
	List(opts StateVersionListOptions) (*StateVersionList, error)
}

type StateVersionStore

type StateVersionStore interface {
	Create(sv *StateVersion) (*StateVersion, error)
	Get(opts StateVersionGetOptions) (*StateVersion, error)
	List(opts StateVersionListOptions) (*StateVersionList, error)
}

type Subscription

type Subscription interface {
	// Event stream for all subscriber's event.
	C() <-chan Event

	// Closes the event stream channel and disconnects from the event service.
	Close() error
}

Subscription represents a stream of events for a subscriber

type TimestampMap added in v0.0.8

type TimestampMap map[string]time.Time

func (TimestampMap) Scan added in v0.0.8

func (m TimestampMap) Scan(src interface{}) error

func (TimestampMap) Value added in v0.0.8

func (m TimestampMap) Value() (driver.Value, error)

type Timestamps added in v0.0.8

type Timestamps struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

func NewTimestamps added in v0.0.8

func NewTimestamps() Timestamps

func (*Timestamps) SetUpdatedAt added in v0.0.8

func (m *Timestamps) SetUpdatedAt(t time.Time)

type Updateable added in v0.0.8

type Updateable interface {
	GetID() string
	SetUpdatedAt(time.Time)
}

Updateable is an obj that records when it was updated.

type VCSRepo added in v0.0.8

type VCSRepo struct {
	Branch            string `json:"branch"`
	DisplayIdentifier string `json:"display-identifier"`
	Identifier        string `json:"identifier"`
	IngressSubmodules bool   `json:"ingress-submodules"`
	OAuthTokenID      string `json:"oauth-token-id"`
	RepositoryHTTPURL string `json:"repository-http-url"`
	ServiceProvider   string `json:"service-provider"`
}

VCSRepo contains the configuration of a VCS integration.

type VCSRepoOptions added in v0.0.8

type VCSRepoOptions struct {
	Branch            *string `json:"branch,omitempty"`
	Identifier        *string `json:"identifier,omitempty"`
	IngressSubmodules *bool   `json:"ingress-submodules,omitempty"`
	OAuthTokenID      *string `json:"oauth-token-id,omitempty"`
}

VCSRepoOptions is used by workspaces, policy sets, and registry modules VCSRepoOptions represents the configuration options of a VCS integration.

type Workspace

type Workspace struct {
	ID string `db:"workspace_id" jsonapi:"primary,workspaces"`

	Timestamps

	AllowDestroyPlan           bool
	AutoApply                  bool
	CanQueueDestroyPlan        bool
	Description                string
	Environment                string
	ExecutionMode              string
	FileTriggersEnabled        bool
	GlobalRemoteState          bool
	Locked                     bool
	MigrationEnvironment       string
	Name                       string
	QueueAllRuns               bool
	SpeculativeEnabled         bool
	StructuredRunOutputEnabled bool
	SourceName                 string
	SourceURL                  string `db:"source_url"`
	TerraformVersion           string
	TriggerPrefixes            CSV
	VCSRepo                    *VCSRepo
	WorkingDirectory           string

	// Workspace belongs to an organization
	Organization *Organization `db:"organizations"`
}

Workspace represents a Terraform Enterprise workspace.

func NewWorkspace

func NewWorkspace(opts WorkspaceCreateOptions, org *Organization) *Workspace

func UpdateWorkspace

func UpdateWorkspace(ws *Workspace, opts WorkspaceUpdateOptions) (*Workspace, error)

func (*Workspace) Actions

func (ws *Workspace) Actions() *WorkspaceActions

func (*Workspace) GetID added in v0.0.8

func (ws *Workspace) GetID() string

func (*Workspace) String added in v0.0.8

func (ws *Workspace) String() string

func (*Workspace) ToggleLock

func (ws *Workspace) ToggleLock(lock bool) error

type WorkspaceActions added in v0.0.8

type WorkspaceActions struct {
	IsDestroyable bool `json:"is-destroyable"`
}

WorkspaceActions represents the workspace actions.

type WorkspaceCreateOptions added in v0.0.8

type WorkspaceCreateOptions struct {
	// Type is a public field utilized by JSON:API to set the resource type via
	// the field tag.  It is not a user-defined value and does not need to be
	// set.  https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,workspaces"`

	// Required when execution-mode is set to agent. The ID of the agent pool
	// belonging to the workspace's organization. This value must not be
	// specified if execution-mode is set to remote or local or if operations is
	// set to true.
	AgentPoolID *string `jsonapi:"attr,agent-pool-id,omitempty"`

	// Whether destroy plans can be queued on the workspace.
	AllowDestroyPlan *bool `jsonapi:"attr,allow-destroy-plan,omitempty"`

	// Whether to automatically apply changes when a Terraform plan is successful.
	AutoApply *bool `jsonapi:"attr,auto-apply,omitempty"`

	// A description for the workspace.
	Description *string `jsonapi:"attr,description,omitempty"`

	// Which execution mode to use. Valid values are remote, local, and agent.
	// When set to local, the workspace will be used for state storage only.
	// This value must not be specified if operations is specified.
	// 'agent' execution mode is not available in Terraform Enterprise.
	ExecutionMode *string `jsonapi:"attr,execution-mode,omitempty"`

	// Whether to filter runs based on the changed files in a VCS push. If
	// enabled, the working directory and trigger prefixes describe a set of
	// paths which must contain changes for a VCS push to trigger a run. If
	// disabled, any push will trigger a run.
	FileTriggersEnabled *bool `jsonapi:"attr,file-triggers-enabled,omitempty"`

	GlobalRemoteState *bool `jsonapi:"attr,global-remote-state,omitempty"`

	// The legacy TFE environment to use as the source of the migration, in the
	// form organization/environment. Omit this unless you are migrating a legacy
	// environment.
	MigrationEnvironment *string `jsonapi:"attr,migration-environment,omitempty"`

	// The name of the workspace, which can only include letters, numbers, -,
	// and _. This will be used as an identifier and must be unique in the
	// organization.
	Name *string `jsonapi:"attr,name"`

	// DEPRECATED. Whether the workspace will use remote or local execution mode.
	// Use ExecutionMode instead.
	Operations *bool `jsonapi:"attr,operations,omitempty"`

	// Whether to queue all runs. Unless this is set to true, runs triggered by
	// a webhook will not be queued until at least one run is manually queued.
	QueueAllRuns *bool `jsonapi:"attr,queue-all-runs,omitempty"`

	// Whether this workspace allows speculative plans. Setting this to false
	// prevents Terraform Cloud or the Terraform Enterprise instance from
	// running plans on pull requests, which can improve security if the VCS
	// repository is public or includes untrusted contributors.
	SpeculativeEnabled *bool `jsonapi:"attr,speculative-enabled,omitempty"`

	// BETA. A friendly name for the application or client creating this
	// workspace. If set, this will be displayed on the workspace as
	// "Created via <SOURCE NAME>".
	SourceName *string `jsonapi:"attr,source-name,omitempty"`

	// BETA. A URL for the application or client creating this workspace. This
	// can be the URL of a related resource in another app, or a link to
	// documentation or other info about the client.
	SourceURL *string `jsonapi:"attr,source-url,omitempty"`

	// BETA. Enable the experimental advanced run user interface.
	// This only applies to runs using Terraform version 0.15.2 or newer,
	// and runs executed using older versions will see the classic experience
	// regardless of this setting.
	StructuredRunOutputEnabled *bool `jsonapi:"attr,structured-run-output-enabled,omitempty"`

	// The version of Terraform to use for this workspace. Upon creating a
	// workspace, the latest version is selected unless otherwise specified.
	TerraformVersion *string `jsonapi:"attr,terraform-version,omitempty"`

	// List of repository-root-relative paths which list all locations to be
	// tracked for changes. See FileTriggersEnabled above for more details.
	TriggerPrefixes []string `jsonapi:"attr,trigger-prefixes,omitempty"`

	// Settings for the workspace's VCS repository. If omitted, the workspace is
	// created without a VCS repo. If included, you must specify at least the
	// oauth-token-id and identifier keys below.
	VCSRepo *VCSRepoOptions `jsonapi:"attr,vcs-repo,omitempty"`

	// A relative path that Terraform will execute within. This defaults to the
	// root of your repository and is typically set to a subdirectory matching the
	// environment when multiple environments exist within the same repository.
	WorkingDirectory *string `jsonapi:"attr,working-directory,omitempty"`
}

WorkspaceCreateOptions represents the options for creating a new workspace.

func (WorkspaceCreateOptions) Valid added in v0.0.8

func (o WorkspaceCreateOptions) Valid() error

type WorkspaceList

type WorkspaceList struct {
	*Pagination
	Items []*Workspace
}

WorkspaceList represents a list of Workspaces.

type WorkspaceListOptions

type WorkspaceListOptions struct {
	// Pagination
	ListOptions

	// Optionally filter workspaces with name matching prefix
	Prefix *string `schema:"search[name],omitempty"`

	// OrganizationName filters workspaces by organization name
	OrganizationName *string

	// A list of relations to include. See available resources https://www.terraform.io/docs/cloud/api/workspaces.html#available-related-resources
	Include *string `schema:"include"`
}

WorkspaceListOptions are options for paginating and filtering a list of Workspaces

type WorkspaceLockOptions added in v0.0.8

type WorkspaceLockOptions struct {
	// Specifies the reason for locking the workspace.
	Reason *string `jsonapi:"attr,reason,omitempty"`
}

WorkspaceLockOptions represents the options for locking a workspace.

type WorkspacePermissions added in v0.0.8

type WorkspacePermissions struct {
	CanDestroy        bool `json:"can-destroy"`
	CanForceUnlock    bool `json:"can-force-unlock"`
	CanLock           bool `json:"can-lock"`
	CanQueueApply     bool `json:"can-queue-apply"`
	CanQueueDestroy   bool `json:"can-queue-destroy"`
	CanQueueRun       bool `json:"can-queue-run"`
	CanReadSettings   bool `json:"can-read-settings"`
	CanUnlock         bool `json:"can-unlock"`
	CanUpdate         bool `json:"can-update"`
	CanUpdateVariable bool `json:"can-update-variable"`
}

WorkspacePermissions represents the workspace permissions.

type WorkspaceQueue

type WorkspaceQueue struct {
	// Active is the currently active run.
	Active *Run
	// Pending is the list of pending runs waiting for the active run to
	// complete.
	Pending []*Run
	// PlanEnqueuer enqueues a plan onto the global queue
	PlanEnqueuer
}

WorkspaceQueue is the queue of runs for a workspace. The queue has at most one active run, which blocks other pending runs. Speculative runs do not block and are therefore not added to the queue.

func (*WorkspaceQueue) Add

func (q *WorkspaceQueue) Add(run *Run) error

Add adds a run to the workspace queue.

func (*WorkspaceQueue) Remove

func (q *WorkspaceQueue) Remove(run *Run) error

Remove removes a run from the queue.

type WorkspaceSpecifier

type WorkspaceSpecifier struct {
	// Specify workspace using its ID
	ID *string `db:"workspace_id"`

	// Specify workspace using its name and organization
	Name             *string
	OrganizationName *string
}

WorkspaceSpecifier is used for identifying an individual workspace. Either ID *or* both Name and OrganizationName must be specfiied.

func (*WorkspaceSpecifier) String added in v0.0.8

func (spec *WorkspaceSpecifier) String() string

func (*WorkspaceSpecifier) Valid added in v0.0.8

func (spec *WorkspaceSpecifier) Valid() error

type WorkspaceStore

type WorkspaceStore interface {
	Create(ws *Workspace) (*Workspace, error)
	Get(spec WorkspaceSpecifier) (*Workspace, error)
	List(opts WorkspaceListOptions) (*WorkspaceList, error)
	Update(spec WorkspaceSpecifier, fn func(*Workspace) error) (*Workspace, error)
	Delete(spec WorkspaceSpecifier) error
}

type WorkspaceUpdateOptions added in v0.0.8

type WorkspaceUpdateOptions struct {
	// Type is a public field utilized by JSON:API to set the resource type via
	// the field tag.  It is not a user-defined value and does not need to be
	// set.  https://jsonapi.org/format/#crud-creating
	Type string `jsonapi:"primary,workspaces"`

	// Required when execution-mode is set to agent. The ID of the agent pool
	// belonging to the workspace's organization. This value must not be
	// specified if execution-mode is set to remote or local or if operations is
	// set to true.
	AgentPoolID *string `jsonapi:"attr,agent-pool-id,omitempty"`

	// Whether destroy plans can be queued on the workspace.
	AllowDestroyPlan *bool `jsonapi:"attr,allow-destroy-plan,omitempty"`

	// Whether to automatically apply changes when a Terraform plan is successful.
	AutoApply *bool `jsonapi:"attr,auto-apply,omitempty"`

	// A new name for the workspace, which can only include letters, numbers, -,
	// and _. This will be used as an identifier and must be unique in the
	// organization. Warning: Changing a workspace's name changes its URL in the
	// API and UI.
	Name *string `jsonapi:"attr,name,omitempty"`

	// A description for the workspace.
	Description *string `jsonapi:"attr,description,omitempty"`

	// Which execution mode to use. Valid values are remote, local, and agent.
	// When set to local, the workspace will be used for state storage only.
	// This value must not be specified if operations is specified.
	// 'agent' execution mode is not available in Terraform Enterprise.
	ExecutionMode *string `jsonapi:"attr,execution-mode,omitempty"`

	// Whether to filter runs based on the changed files in a VCS push. If
	// enabled, the working directory and trigger prefixes describe a set of
	// paths which must contain changes for a VCS push to trigger a run. If
	// disabled, any push will trigger a run.
	FileTriggersEnabled *bool `jsonapi:"attr,file-triggers-enabled,omitempty"`

	GlobalRemoteState *bool `jsonapi:"attr,global-remote-state,omitempty"`

	// DEPRECATED. Whether the workspace will use remote or local execution mode.
	// Use ExecutionMode instead.
	Operations *bool `jsonapi:"attr,operations,omitempty"`

	// Whether to queue all runs. Unless this is set to true, runs triggered by
	// a webhook will not be queued until at least one run is manually queued.
	QueueAllRuns *bool `jsonapi:"attr,queue-all-runs,omitempty"`

	// Whether this workspace allows speculative plans. Setting this to false
	// prevents Terraform Cloud or the Terraform Enterprise instance from
	// running plans on pull requests, which can improve security if the VCS
	// repository is public or includes untrusted contributors.
	SpeculativeEnabled *bool `jsonapi:"attr,speculative-enabled,omitempty"`

	// BETA. Enable the experimental advanced run user interface.
	// This only applies to runs using Terraform version 0.15.2 or newer,
	// and runs executed using older versions will see the classic experience
	// regardless of this setting.
	StructuredRunOutputEnabled *bool `jsonapi:"attr,structured-run-output-enabled,omitempty"`

	// The version of Terraform to use for this workspace.
	TerraformVersion *string `jsonapi:"attr,terraform-version,omitempty"`

	// List of repository-root-relative paths which list all locations to be
	// tracked for changes. See FileTriggersEnabled above for more details.
	TriggerPrefixes []string `jsonapi:"attr,trigger-prefixes,omitempty"`

	// To delete a workspace's existing VCS repo, specify null instead of an
	// object. To modify a workspace's existing VCS repo, include whichever of
	// the keys below you wish to modify. To add a new VCS repo to a workspace
	// that didn't previously have one, include at least the oauth-token-id and
	// identifier keys.
	VCSRepo *VCSRepoOptions `jsonapi:"attr,vcs-repo,omitempty"`

	// A relative path that Terraform will execute within. This defaults to the
	// root of your repository and is typically set to a subdirectory matching
	// the environment when multiple environments exist within the same
	// repository.
	WorkingDirectory *string `jsonapi:"attr,working-directory,omitempty"`
}

WorkspaceUpdateOptions represents the options for updating a workspace.

func (WorkspaceUpdateOptions) Valid added in v0.0.8

func (o WorkspaceUpdateOptions) Valid() error

Directories

Path Synopsis
Package agent provides a daemon capable of running remote operations on behalf of a user.
Package agent provides a daemon capable of running remote operations on behalf of a user.
mock
Package mock provides mocks for the parent agent package
Package mock provides mocks for the parent agent package
Package app implements services, co-ordinating between the layers of the project.
Package app implements services, co-ordinating between the layers of the project.
cmd
Package cmd provides CLI functionality.
Package cmd provides CLI functionality.
otf command
otfd command
Package http provides an HTTP interface allowing HTTP clients to interact with OTF.
Package http provides an HTTP interface allowing HTTP clients to interact with OTF.
Package inmem implements a layer of services in memory using purely Go constructs.
Package inmem implements a layer of services in memory using purely Go constructs.
Package mock implements mocked services.
Package mock implements mocked services.
Package sql implements persistent storage using the sql database.
Package sql implements persistent storage using the sql database.

Jump to

Keyboard shortcuts

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