otf

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2021 License: MPL-2.0 Imports: 24 Imported by: 0

README

OTF: Open Terraforming Framework

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:

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

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

    otf login
    
  6. Create an organization:

    otf organizations new mycorp --email=sysadmin@mycorp.co
    
  7. 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
    
  8. 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 (
	// 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 (
	DefaultAutoQueueRuns       = true
	DefaultConfigurationSource = "tfe-api"
)
View Source
const (
	DefaultSessionTimeout         = 20160
	DefaultSessionExpiration      = 20160
	DefaultCollaboratorAuthPolicy = "password"
	DefaultCostEstimationEnabled  = true
)
View Source
const (
	DefaultPageNumber = 1
	DefaultPageSize   = 20
	MaxPageSize       = 100

	DefaultUserID   = "user-123"
	DefaultUsername = "otf"
)
View Source
const (
	LocalStateFilename  = "terraform.tfstate"
	PlanFilename        = "plan.out"
	JSONPlanFilename    = "plan.out.json"
	ApplyOutputFilename = "apply.out"
)
View Source
const (
	DefaultAllowDestroyPlan    = true
	DefaultFileTriggersEnabled = true
	DefaultTerraformVersion    = "0.15.4"
	DefaultExecutionMode       = "remote"
)
View Source
const (
	// DefaultRefresh specifies that the state be refreshed prior to running a
	// plan
	DefaultRefresh = true
)

Variables

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 = []tfe.RunStatus{
		tfe.RunApplyQueued,
		tfe.RunApplying,
		tfe.RunConfirmed,
		tfe.RunPlanQueued,
		tfe.RunPlanned,
		tfe.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 (
	DefaultOrganizationPermissions = tfe.OrganizationPermissions{
		CanCreateWorkspace: true,
		CanUpdate:          true,
		CanDestroy:         true,
	}
)
View Source
var (
	ErrInvalidConfigurationVersionGetOptions = errors.New("invalid configuration version get options")
)
View Source
var (
	ErrInvalidStateVersionGetOptions = errors.New("invalid state version get options")
)

Functions

func GenerateID

func GenerateID(prefix string) string

GenerateID generates a unique identifier with the given prefix

func GenerateRandomString

func GenerateRandomString(size int) string

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

func GetChunk

func GetChunk(p []byte, opts GetChunkOptions, complete bool) ([]byte, error)

GetChunk retrieves a chunk of bytes from a byte slice. The first chunk in the slice is prefixed with a special byte. If complete is true then the last chunk in the slice is suffixed with a special byte.

func Int

func Int(i int) *int

func Int64

func Int64(i int64) *int64

func IsNotFound

func IsNotFound(err error) bool

func NewBlobID

func NewBlobID() string

NewBlobID generates a unique blob ID

func NewPagination

func NewPagination(opts tfe.ListOptions, count int) *tfe.Pagination

NewPagination constructs a Pagination obj.

func SanitizeListOptions

func SanitizeListOptions(opts *tfe.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 *tfe.OrganizationUpdateOptions) error

Types

type Apply

type Apply struct {
	ID string

	gorm.Model

	ResourceAdditions    int
	ResourceChanges      int
	ResourceDestructions int
	Status               tfe.ApplyStatus
	StatusTimestamps     *tfe.ApplyStatusTimestamps

	// Logs is the blob ID for the log output from a terraform apply
	LogsBlobID string
}

func (*Apply) Do

func (a *Apply) Do(run *Run, exe *Executor) error

func (*Apply) GetLogsBlobID

func (a *Apply) GetLogsBlobID() string

func (*Apply) UpdateResources

func (a *Apply) UpdateResources(bs BlobStore) error

UpdateResources parses the output from terraform apply to determine the number and type of resource changes applied and updates the apply object accordingly.

func (*Apply) UpdateStatus

func (a *Apply) UpdateStatus(status tfe.ApplyStatus)

type ApplyFinishOptions

type ApplyFinishOptions 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,applies"`

	ResourceAdditions    int `jsonapi:"attr,resource-additions"`
	ResourceChanges      int `jsonapi:"attr,resource-changes"`
	ResourceDestructions int `jsonapi:"attr,resource-destructions"`
}

ApplyFinishOptions represents the options for finishing an apply.

type ApplyService

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

type BlobStore

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

	// Get fetches a blob chunk
	GetChunk(string, GetChunkOptions) ([]byte, error)

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

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

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

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 ConfigurationVersion

type ConfigurationVersion struct {
	ID string

	gorm.Model

	AutoQueueRuns    bool
	Error            string
	ErrorMessage     string
	Source           tfe.ConfigurationSource
	Speculative      bool
	Status           tfe.ConfigurationStatus
	StatusTimestamps *tfe.CVStatusTimestamps

	// BlobID is the ID of the blob containing the configuration
	BlobID string

	// Configuration Version belongs to a Workspace
	Workspace *Workspace
}

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

type ConfigurationVersionFactory

type ConfigurationVersionFactory struct {
	WorkspaceService WorkspaceService
}

ConfigurationVersionFactory creates ConfigurationVersion objects

func (*ConfigurationVersionFactory) NewConfigurationVersion

func (f *ConfigurationVersionFactory) NewConfigurationVersion(workspaceID string, opts *tfe.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
}

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

type ConfigurationVersionList

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

ConfigurationVersionList represents a list of configuration versions.

type ConfigurationVersionListOptions

type ConfigurationVersionListOptions struct {
	tfe.ListOptions

	// Filter by run statuses (with an implicit OR condition)
	Statuses []tfe.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 *tfe.ConfigurationVersionCreateOptions) (*ConfigurationVersion, error)
	Get(id string) (*ConfigurationVersion, error)
	GetLatest(workspaceID string) (*ConfigurationVersion, error)
	List(workspaceID string, opts tfe.ConfigurationVersionListOptions) (*ConfigurationVersionList, error)
	Upload(id string, payload []byte) error
	Download(id string) ([]byte, error)
}

type Entitlements

type Entitlements struct {
	*tfe.Entitlements
}

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

func DefaultEntitlements

func DefaultEntitlements(organizationID string) *Entitlements

DefaultEntitlements constructs an Entitlements struct with currently supported entitlements.

type ErrInvalidRunStatusTransition

type ErrInvalidRunStatusTransition struct {
	From tfe.RunStatus
	To   tfe.RunStatus
}

func (ErrInvalidRunStatusTransition) Error

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
}

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"
	RunCanceled           EventType = "run_canceled"
	RunApplied            EventType = "run_applied"
	RunPlanned            EventType = "run_planned"
	RunPlannedAndFinished EventType = "run_planned_and_finished"
	PlanQueued            EventType = "plan_queued"
	ApplyQueued           EventType = "apply_queued"
)

type Executor

type Executor struct {
	JobService

	RunService                  RunService
	ConfigurationVersionService ConfigurationVersionService
	StateVersionService         StateVersionService

	// Current working directory
	Path string

	// logger
	logr.Logger
	// contains filtered or unexported fields
}

Executor executes a job, providing it with services, temp directory etc, capturing its stdout

func NewExecutor

func NewExecutor(logger logr.Logger, rs RunService, cvs ConfigurationVersionService, svs StateVersionService, agentID string) (*Executor, error)

NewExecutor constructs an Executor.

func (*Executor) Cancel

func (e *Executor) Cancel(force bool)

Cancel terminates execution. Force controls whether termination is graceful or not. Performed on a best-effort basis - the func or process may have finished before they are cancelled, in which case only the next func or process will be stopped from executing.

func (*Executor) Execute

func (e *Executor) Execute(job Job) (err error)

Execute performs the full lifecycle of executing a job: marking it as started, running the job, and then marking it as finished. Its logs are captured and forwarded.

func (*Executor) RunCLI

func (e *Executor) RunCLI(name string, args ...string) error

RunCLI executes a CLI process in the executor.

func (*Executor) RunFunc

func (e *Executor) RunFunc(fn ExecutorFunc) error

RunFunc invokes a func in the executor.

type ExecutorFunc

type ExecutorFunc func(context.Context, *Executor) error

ExecutorFunc is a func that can be invoked in the executor

type GetChunkOptions

type GetChunkOptions struct {
	// The maximum number of bytes of logs to return to the client
	Limit int `schema:"limit"`

	// The start position in the logs from which to send to the client
	Offset int `schema:"offset"`
}

type Job

type Job interface {
	// GetID gets the ID of the job
	GetID() string
	// GetStatus gets the status of the job
	GetStatus() string
	// Do does the piece of work in an execution environment
	Do(*Executor) error
}

Job represents a piece of work to be done

type JobFinishOptions

type JobFinishOptions struct {
	Errored bool
}

type JobLogsUploader

type JobLogsUploader interface {
	// UploadLogs uploads a chunk of output from the job.
	UploadLogs(id string, logs []byte, opts PutChunkOptions) error
}

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(id string, opts JobStartOptions) (Job, error)
	// Finish is called by an agent when it finishes a job.
	Finish(id string, opts JobFinishOptions) (Job, error)

	JobLogsUploader
}

type JobStartOptions

type JobStartOptions struct {
	AgentID string
}

type JobWriter

type JobWriter struct {
	// JobLogsUploader uploads a chunk of logs to the server
	JobLogsUploader

	// ID of job
	ID string

	logr.Logger
}

JobWriter writes logs on behalf of a job.

func (*JobWriter) Close

func (jw *JobWriter) Close() error

Close must be called to complete writing job logs

func (*JobWriter) Write

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

Write uploads a chunk of logs to the server.

type Organization

type Organization struct {
	ID string

	gorm.Model

	Name                   string
	CollaboratorAuthPolicy tfe.AuthPolicyType
	CostEstimationEnabled  bool
	Email                  string
	OwnersTeamSAMLRoleID   string
	Permissions            *tfe.OrganizationPermissions
	SAMLEnabled            bool
	SessionRemember        int
	SessionTimeout         int
	TrialExpiresAt         time.Time
	TwoFactorConformant    bool
}

Organization represents a Terraform Enterprise organization.

func NewOrganization

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

type OrganizationList

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

OrganizationList represents a list of Organizations.

type OrganizationService

type OrganizationService interface {
	Create(opts *tfe.OrganizationCreateOptions) (*Organization, error)
	Get(name string) (*Organization, error)
	List(opts tfe.OrganizationListOptions) (*OrganizationList, error)
	Update(name string, opts *tfe.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 tfe.OrganizationListOptions) (*OrganizationList, error)
	Update(name string, fn func(*Organization) error) (*Organization, error)
	Delete(name string) error
}

type Phase

type Phase interface {
	GetLogsBlobID() string
	Do(*Run, *Executor) error
}

Phase implementations represent the phases that make up a run: a plan and an apply.

type Plan

type Plan struct {
	ID string

	gorm.Model

	ResourceAdditions    int
	ResourceChanges      int
	ResourceDestructions int
	Status               tfe.PlanStatus
	StatusTimestamps     *tfe.PlanStatusTimestamps

	// LogsBlobID is the blob ID for the log output from a terraform plan
	LogsBlobID string

	// PlanFileBlobID is the blob ID of the execution plan file in binary format
	PlanFileBlobID string

	// PlanJSONBlobID is the blob ID of the execution plan file in json format
	PlanJSONBlobID string
}

Plan represents a Terraform Enterprise plan.

func (*Plan) Do

func (p *Plan) Do(run *Run, exe *Executor) error

func (*Plan) GetLogsBlobID

func (p *Plan) GetLogsBlobID() string

func (*Plan) HasChanges

func (p *Plan) HasChanges() bool

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

func (*Plan) UpdateResources

func (p *Plan) UpdateResources(bs BlobStore) error

UpdateResources parses the plan file produced from terraform plan to determine the number and type of resource changes planned and updates the plan object accordingly.

func (*Plan) UpdateStatus

func (p *Plan) UpdateStatus(status tfe.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() (adds int, updates int, deletes int)

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

type PlanFinishOptions

type PlanFinishOptions 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,plans"`

	ResourceAdditions    int `jsonapi:"attr,resource-additions"`
	ResourceChanges      int `jsonapi:"attr,resource-changes"`
	ResourceDestructions int `jsonapi:"attr,resource-destructions"`
}

PlanFinishOptions represents the options for finishing a plan.

type PlanService

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

type PutChunkOptions

type PutChunkOptions struct {
	// 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 Run

type Run struct {
	ID string

	gorm.Model

	ForceCancelAvailableAt time.Time
	IsDestroy              bool
	Message                string
	Permissions            *tfe.RunPermissions
	PositionInQueue        int
	Refresh                bool
	RefreshOnly            bool
	Status                 tfe.RunStatus
	StatusTimestamps       *tfe.RunStatusTimestamps
	ReplaceAddrs           []string
	TargetAddrs            []string

	// Relations
	Plan                 *Plan
	Apply                *Apply
	Workspace            *Workspace
	ConfigurationVersion *ConfigurationVersion
}

func (*Run) Actions

func (r *Run) Actions() *tfe.RunActions

Actions lists which actions are currently invokable.

func (*Run) ActivePhase

func (r *Run) ActivePhase() (Phase, error)

ActivePhase retrieves the currently active phase

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(exe *Executor) error

func (*Run) Finish

func (r *Run) Finish(bs BlobStore) (*Event, error)

Finish updates the run to reflect the current phase having finished. An event is emitted reflecting the run's new status.

func (*Run) ForceCancel

func (r *Run) ForceCancel() error

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

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) Start

func (r *Run) Start() error

Start starts a run phase.

func (*Run) UpdateStatus

func (r *Run) UpdateStatus(status tfe.RunStatus)

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

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 *tfe.RunCreateOptions) (*Run, error)

NewRun constructs a run object.

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
}

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

type RunList

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

RunList represents a list of runs.

type RunListOptions

type RunListOptions struct {
	tfe.RunListOptions

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

	// Filter by workspace ID
	WorkspaceID *string
}

RunListOptions are options for paginating and filtering a list of runs

type RunService

type RunService interface {
	Create(opts *tfe.RunCreateOptions) (*Run, error)
	Get(id string) (*Run, error)
	List(opts RunListOptions) (*RunList, error)
	Apply(id string, opts *tfe.RunApplyOptions) error
	Discard(id string, opts *tfe.RunDiscardOptions) error
	Cancel(id string, opts *tfe.RunCancelOptions) error
	ForceCancel(id string, opts *tfe.RunForceCancelOptions) error
	EnqueuePlan(id string) error
	GetPlanLogs(id string, opts GetChunkOptions) ([]byte, error)
	GetApplyLogs(id string, opts GetChunkOptions) ([]byte, error)
	GetPlanJSON(id string) ([]byte, error)
	GetPlanFile(id string) ([]byte, error)
	UploadPlan(runID string, plan []byte, json bool) error

	JobService
}

RunService implementations allow interactions with runs

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(id string, 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

	gorm.Model

	Serial       int64
	VCSCommitSHA string
	VCSCommitURL string

	// BlobID is ID of the binary object containing the state
	BlobID string

	// State version belongs to a workspace
	Workspace *Workspace

	Outputs []*StateVersionOutput

	// State version has many outputs
	StateVersionOutputs []StateVersionOutput
}

StateVersion represents a Terraform Enterprise state version.

func (*StateVersion) DownloadURL

func (r *StateVersion) DownloadURL() string

type StateVersionFactory

type StateVersionFactory struct {
	WorkspaceService WorkspaceService
	BlobStore        BlobStore
}

func (*StateVersionFactory) NewStateVersion

func (f *StateVersionFactory) NewStateVersion(workspaceID string, opts tfe.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
}

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

type StateVersionList

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

StateVersionList represents a list of state versions.

type StateVersionOutput

type StateVersionOutput struct {
	ID string

	gorm.Model

	Name      string
	Sensitive bool
	Type      string
	Value     string

	// StateVersionOutput belongs to State Version
	StateVersionID uint
}

type StateVersionOutputList

type StateVersionOutputList []*StateVersionOutput

type StateVersionService

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

type StateVersionStore

type StateVersionStore interface {
	Create(sv *StateVersion) (*StateVersion, error)
	Get(opts StateVersionGetOptions) (*StateVersion, error)
	List(opts tfe.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 Workspace

type Workspace struct {
	ID string

	gorm.Model

	AllowDestroyPlan           bool
	AutoApply                  bool
	CanQueueDestroyPlan        bool
	Description                string
	Environment                string
	ExecutionMode              string
	FileTriggersEnabled        bool
	GlobalRemoteState          bool
	Locked                     bool
	MigrationEnvironment       string
	Name                       string
	Permissions                *tfe.WorkspacePermissions
	QueueAllRuns               bool
	SpeculativeEnabled         bool
	SourceName                 string
	SourceURL                  string
	StructuredRunOutputEnabled bool
	TerraformVersion           string
	VCSRepo                    *tfe.VCSRepo
	WorkingDirectory           string
	ResourceCount              int
	ApplyDurationAverage       time.Duration
	PlanDurationAverage        time.Duration
	PolicyCheckFailures        int
	RunFailures                int
	RunsCount                  int

	TriggerPrefixes []string

	// Workspace belongs to an organization
	Organization *Organization
}

Workspace represents a Terraform Enterprise workspace.

func NewWorkspace

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

func UpdateWorkspace

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

func (*Workspace) Actions

func (ws *Workspace) Actions() *tfe.WorkspaceActions

func (*Workspace) ToggleLock

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

type WorkspaceList

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

WorkspaceList represents a list of Workspaces.

type WorkspaceListOptions

type WorkspaceListOptions struct {
	// Pagination
	tfe.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 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 WorkspaceService

type WorkspaceService interface {
	Create(org string, opts *tfe.WorkspaceCreateOptions) (*Workspace, error)
	Get(spec WorkspaceSpecifier) (*Workspace, error)
	List(opts WorkspaceListOptions) (*WorkspaceList, error)
	Update(spec WorkspaceSpecifier, opts *tfe.WorkspaceUpdateOptions) (*Workspace, error)
	Lock(id string, opts tfe.WorkspaceLockOptions) (*Workspace, error)
	Unlock(id string) (*Workspace, error)
	Delete(spec WorkspaceSpecifier) error
}

type WorkspaceSpecifier

type WorkspaceSpecifier struct {
	// Specify workspace using its ID
	ID *string

	// 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.

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
}

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 filestore provides filesystem storage for binary objects (blobs).
Package filestore provides filesystem storage for binary objects (blobs).
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 sqlite implements persistent storage using the sqlite database.
Package sqlite implements persistent storage using the sqlite database.

Jump to

Keyboard shortcuts

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