Documentation ¶
Overview ¶
Package run is responsible for OTF runs, the primary mechanism for executing terraform
Index ¶
- Constants
- Variables
- func CompilePlanReports(planJSON []byte) (resources Report, outputs Report, err error)
- func NewCommand(client *otfapi.Client) *cobra.Command
- type CLI
- type Change
- type ChangeAction
- type Client
- func (c *Client) Get(ctx context.Context, runID resource.ID) (*Run, error)
- func (c *Client) GetLockFile(ctx context.Context, runID resource.ID) ([]byte, error)
- func (c *Client) GetPlanFile(ctx context.Context, runID resource.ID, format PlanFormat) ([]byte, error)
- func (c *Client) ListRuns(ctx context.Context, opts ListOptions) (*resource.Page[*Run], error)
- func (c *Client) UploadLockFile(ctx context.Context, runID resource.ID, lockfile []byte) error
- func (c *Client) UploadPlanFile(ctx context.Context, runID resource.ID, plan []byte, format PlanFormat) error
- type ConfigurationVersionService
- type CreateOptions
- type ListOptions
- type MetricsCollector
- type Operation
- type Options
- type PeriodReport
- type Phase
- func (p *Phase) Done() bool
- func (p *Phase) ElapsedTime(now time.Time) time.Duration
- func (p *Phase) HasChanges() bool
- func (p *Phase) HasStarted() bool
- func (p *Phase) StartedAt() time.Time
- func (p *Phase) StatusTimestamp(status PhaseStatus) (time.Time, error)
- func (p *Phase) String() string
- func (p *Phase) UpdateStatus(status PhaseStatus)
- type PhaseFinishOptions
- type PhaseStartOptions
- type PhaseStatus
- type PhaseStatusTimestamp
- type PlanFile
- type PlanFileOptions
- type PlanFormat
- type Report
- type Reporter
- type ResourceChange
- type Run
- func (r *Run) Cancel(isUser, force bool) error
- func (r *Run) Cancelable() bool
- func (r *Run) Confirmable() bool
- func (r *Run) Discard() error
- func (r *Run) Discardable() bool
- func (r *Run) Done() bool
- func (r *Run) ElapsedTime(now time.Time) time.Duration
- func (r *Run) EnqueueApply() error
- func (r *Run) EnqueuePlan() error
- func (r *Run) Finish(phase internal.PhaseType, opts PhaseFinishOptions) (autoapply bool, err error)
- func (r *Run) ForceCancelAvailableAt() *time.Time
- func (r *Run) ForceCancelable() bool
- func (r *Run) HasChanges() bool
- func (r *Run) HasStarted() bool
- func (r *Run) InProgress() bool
- func (r *Run) IsAPISource() bool
- func (r *Run) IsCLISource() bool
- func (r *Run) IsGithubSource() bool
- func (r *Run) IsGitlabSource() bool
- func (r *Run) IsUISource() bool
- func (r *Run) PeriodReport(now time.Time) (report PeriodReport)
- func (r *Run) Phase() internal.PhaseType
- func (r *Run) Queued() bool
- func (r *Run) Start() error
- func (r *Run) StartedAt() time.Time
- func (r *Run) StatusTimestamp(status Status) (time.Time, error)
- func (r *Run) String() string
- type Service
- func (s *Service) AddHandlers(r *mux.Router)
- func (s *Service) AfterCancelRun(hook func(context.Context, *Run) error)
- func (s *Service) AfterEnqueueApply(hook func(context.Context, *Run) error)
- func (s *Service) AfterEnqueuePlan(hook func(context.Context, *Run) error)
- func (s *Service) AfterForceCancelRun(hook func(context.Context, *Run) error)
- func (s *Service) Apply(ctx context.Context, runID resource.ID) error
- func (s *Service) Cancel(ctx context.Context, runID resource.ID) error
- func (s *Service) Create(ctx context.Context, workspaceID resource.ID, opts CreateOptions) (*Run, error)
- func (s *Service) Delete(ctx context.Context, runID resource.ID) error
- func (s *Service) Discard(ctx context.Context, runID resource.ID) error
- func (s *Service) EnqueuePlan(ctx context.Context, runID resource.ID) (run *Run, err error)
- func (s *Service) FinishPhase(ctx context.Context, runID resource.ID, phase internal.PhaseType, ...) (*Run, error)
- func (s *Service) ForceCancel(ctx context.Context, runID resource.ID) error
- func (s *Service) Get(ctx context.Context, runID resource.ID) (*Run, error)
- func (s *Service) GetLockFile(ctx context.Context, runID resource.ID) ([]byte, error)
- func (s *Service) GetPlanFile(ctx context.Context, runID resource.ID, format PlanFormat) ([]byte, error)
- func (s *Service) List(ctx context.Context, opts ListOptions) (*resource.Page[*Run], error)
- func (f Service) NewRun(ctx context.Context, workspaceID resource.ID, opts CreateOptions) (*Run, error)
- func (s *Service) StartPhase(ctx context.Context, runID resource.ID, phase internal.PhaseType, ...) (*Run, error)
- func (s *Service) UploadLockFile(ctx context.Context, runID resource.ID, file []byte) error
- func (s *Service) UploadPlanFile(ctx context.Context, runID resource.ID, plan []byte, format PlanFormat) error
- func (s *Service) Watch(ctx context.Context) (<-chan pubsub.Event[*Run], func())
- type Source
- type Spawner
- type Status
- type StatusPeriod
- type StatusTimestamp
- type Timeout
- type VCSProviderService
- type Variable
- type WatchOptions
Constants ¶
const ReporterLockID int64 = 179366396344335597
ReporterLockID is a unique ID guaranteeing only one reporter on a cluster is running at any time.
const TimeoutLockID int64 = 179366396344335598
TimeoutLockID is a unique ID guaranteeing only one timeout daemon on a cluster is running at any time.
Variables ¶
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") // ErrPhaseAlreadyStarted = errors.New("phase already started") )
var ( ActiveRun = []Status{ RunApplyQueued, RunApplying, RunConfirmed, RunPlanQueued, RunPlanned, RunPlanning, } IncompleteRun = append(ActiveRun, RunPending) )
var ErrInvalidRunStateTransition = errors.New("invalid run state transition")
Functions ¶
func CompilePlanReports ¶ added in v0.0.51
CompilePlanReports compiles reports of planned changes from a JSON representation of a plan file: one report for planned *resources*, and another for planned *outputs*.
Types ¶
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 Client ¶
func (*Client) GetLockFile ¶
func (*Client) GetPlanFile ¶
func (*Client) UploadLockFile ¶
func (*Client) UploadPlanFile ¶
type ConfigurationVersionService ¶
type ConfigurationVersionService configversion.Service
Alias services so they don't conflict when nested together in struct
type CreateOptions ¶ added in v0.1.8
type CreateOptions struct { IsDestroy *bool Refresh *bool RefreshOnly *bool Message *string // Specifies the configuration version to use for this run. If the // configuration version ID is nil, the run will be created using the // workspace's latest configuration version. ConfigurationVersionID *resource.ID TargetAddrs []string ReplaceAddrs []string AutoApply *bool Source Source TerraformVersion *string AllowEmptyApply *bool // PlanOnly specifies if this is a speculative, plan-only run that // Terraform cannot apply. Takes precedence over whether the // configuration version is marked as speculative or not. PlanOnly *bool Variables []Variable // contains filtered or unexported fields }
CreateOptions represents the options for creating a new run. See api.types.RunCreateOptions for documentation on each field.
type ListOptions ¶ added in v0.1.8
type ListOptions struct { resource.PageOptions // Filter by workspace ID WorkspaceID *resource.ID `schema:"workspace_id,omitempty"` // Filter by organization name Organization *string `schema:"organization_name,omitempty"` // Filter by workspace name WorkspaceName *string `schema:"workspace_name,omitempty"` // Filter by run statuses (with an implicit OR condition) Statuses []Status `schema:"statuses,omitempty"` // Filter by plan-only runs PlanOnly *bool `schema:"-"` // Filter by sources Sources []Source // Filter by commit SHA that triggered a run CommitSHA *string // Filter by VCS user's username that triggered a run VCSUsername *string }
ListOptions are options for paginating and filtering a list of runs
type MetricsCollector ¶ added in v0.3.4
type MetricsCollector struct { Service *Service // contains filtered or unexported fields }
type Options ¶
type Options struct { Authorizer *authz.Authorizer VCSEventSubscriber vcs.Subscriber WorkspaceService *workspace.Service OrganizationService *organization.Service ConfigVersionService *configversion.Service ReleasesService *releases.Service VCSProviderService *vcsprovider.Service TokensService *tokens.Service logr.Logger internal.Cache *sql.DB *tfeapi.Responder *surl.Signer html.Renderer *sql.Listener }
type PeriodReport ¶ added in v0.1.17
type PeriodReport struct { TotalTime time.Duration `json:"total_time"` Periods []StatusPeriod `json:"periods"` }
func (PeriodReport) Percentage ¶ added in v0.1.17
func (r PeriodReport) Percentage(i int) float64
type Phase ¶
type Phase struct { RunID resource.ID `json:"run_id"` Status PhaseStatus `json:"status"` // Timestamps of when a state transition occured. Ordered earliest // first. StatusTimestamps []PhaseStatusTimestamp `json:"status_timestamps"` internal.PhaseType `json:"phase"` // report of planned or applied resource changes ResourceReport *Report `json:"resource_report"` // report of planned or applied output changes OutputReport *Report `json:"output_report"` }
Phase is a section of work performed by a run.
func (*Phase) ElapsedTime ¶ added in v0.1.17
ElapsedTime returns the time taken for the phase to complete its running state. If the run is yet to enter a running state then it returns 0. If the running state is still in progress then it returns the time since entering the running state.
func (*Phase) HasChanges ¶
func (*Phase) HasStarted ¶ added in v0.1.17
func (*Phase) StartedAt ¶ added in v0.1.17
StartedAt returns the time the phase started running, returning zero time if it is yet to start running.
func (*Phase) StatusTimestamp ¶
func (p *Phase) StatusTimestamp(status PhaseStatus) (time.Time, error)
StatusTimestamp looks up the timestamp for a status
func (*Phase) UpdateStatus ¶
func (p *Phase) UpdateStatus(status PhaseStatus)
type PhaseFinishOptions ¶
type PhaseFinishOptions struct {
Errored bool `json:"errored,omitempty"`
}
PhaseFinishOptions report the status of a phase upon finishing.
type PhaseStartOptions ¶
type PhaseStatus ¶
type PhaseStatus string
const ( PhasePending PhaseStatus = "pending" PhaseQueued PhaseStatus = "queued" PhaseRunning PhaseStatus = "running" PhaseFinished PhaseStatus = "finished" PhaseCanceled PhaseStatus = "canceled" PhaseErrored PhaseStatus = "errored" PhaseUnreachable PhaseStatus = "unreachable" )
func (PhaseStatus) String ¶
func (s PhaseStatus) String() string
type PhaseStatusTimestamp ¶
type PhaseStatusTimestamp struct { Status PhaseStatus `json:"status"` Timestamp time.Time `json:"timestamp"` }
type PlanFile ¶
type PlanFile struct { ResourceChanges []ResourceChange `json:"resource_changes"` OutputChanges map[string]Change `json:"output_changes"` }
PlanFile represents the schema of a plan file
type PlanFileOptions ¶
type PlanFileOptions struct {
Format PlanFormat `schema:"format,required"`
}
PlanFileOptions are options for the plan file API
type PlanFormat ¶
type PlanFormat string
type Report ¶ added in v0.0.51
type Report struct { Additions int `json:"additions"` Changes int `json:"changes"` Destructions int `json:"destructions"` }
Report reports a summary of additions, changes, and deletions of resources in a plan or an apply.
func ParseApplyOutput ¶
func (Report) HasChanges ¶ added in v0.0.51
type Reporter ¶
type Reporter struct { logr.Logger *internal.HostnameService Configs reporterConfigClient Workspaces reporterWorkspaceClient VCS reporterVCSClient Runs reporterRunClient // Cache most recently set status for each incomplete run to ensure the // same status is not set more than once on an upstream VCS provider. // This is important to avoid hitting rate limits on VCS providers, e.g. // GitHub has a limit of 1000 status updates on a commit: // // https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28#create-a-commit-status // // Key is the run ID. Cache map[resource.ID]vcs.Status }
Reporter reports back to VCS providers the current status of VCS-triggered runs.
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 resource.ID `jsonapi:"primary,runs"` CreatedAt time.Time `jsonapi:"attribute" json:"created_at"` IsDestroy bool `jsonapi:"attribute" json:"is_destroy"` CancelSignaledAt *time.Time `jsonapi:"attribute" json:"cancel_signaled_at"` Message string `jsonapi:"attribute" json:"message"` Organization string `jsonapi:"attribute" json:"organization"` Refresh bool `jsonapi:"attribute" json:"refresh"` RefreshOnly bool `jsonapi:"attribute" json:"refresh_only"` ReplaceAddrs []string `jsonapi:"attribute" json:"replace_addrs"` PositionInQueue int `jsonapi:"attribute" json:"position_in_queue"` TargetAddrs []string `jsonapi:"attribute" json:"target_addrs"` TerraformVersion string `jsonapi:"attribute" json:"terraform_version"` AllowEmptyApply bool `jsonapi:"attribute" json:"allow_empty_apply"` AutoApply bool `jsonapi:"attribute" json:"auto_apply"` PlanOnly bool `jsonapi:"attribute" json:"plan_only"` Source Source `jsonapi:"attribute" json:"source"` Status Status `jsonapi:"attribute" json:"status"` WorkspaceID resource.ID `jsonapi:"attribute" json:"workspace_id"` ConfigurationVersionID resource.ID `jsonapi:"attribute" json:"configuration_version_id"` ExecutionMode workspace.ExecutionMode `jsonapi:"attribute" json:"execution_mode"` Variables []Variable `jsonapi:"attribute" json:"variables"` Plan Phase `jsonapi:"attribute" json:"plan"` Apply Phase `jsonapi:"attribute" json:"apply"` // Timestamps of when a state transition occured. Ordered earliest // first. StatusTimestamps []StatusTimestamp `jsonapi:"attribute" json:"status_timestamps"` Latest bool `jsonapi:"attribute" json:"latest"` // is latest run for workspace // IngressAttributes is non-nil if run was triggered by a VCS event. IngressAttributes *configversion.IngressAttributes `jsonapi:"attribute" json:"ingress_attributes"` // Username of user who created the run. This is nil if the run was // instead triggered by a VCS event. CreatedBy *string // OTF doesn't support cost estimation but some go-tfe API tests expect // a run to enter the RunCostEstimated state, and this boolean // determines whether to enter that state upon finishing a plan. CostEstimationEnabled bool }
Run is a terraform run.
func (*Run) Cancel ¶
Cancel run. Depending upon whether the run is currently in-progress, the run is either immediately canceled and its status updated to reflect that, or CancelSignaledAt is set to the current time to indicate that a cancelation signal should be sent to the process executing the run.
The isUser arg should be set to true if a user is directly instigating the cancelation; otherwise it should be set to false, i.e. the job service has canceled a job and is now canceling the corresponding run.
The force arg when set to true forceably cancels the run. This is only allowed when an attempt has already been made to cancel the run non-forceably. The force arg is only respected when isUser is true.
func (*Run) Cancelable ¶
Cancelable determines whether run can be cancelled.
func (*Run) Confirmable ¶
Confirmable determines whether run can be confirmed.
func (*Run) Discardable ¶
Discardable determines whether run can be discarded.
func (*Run) Done ¶
Done determines whether run has reached an end state, e.g. applied, discarded, etc.
func (*Run) ElapsedTime ¶ added in v0.1.17
ElapsedTime returns the total time the run has taken thus far. If the run has completed, then it is the time taken from entering the pending state (creation) through to completion. Otherwise it is the time since entering the pending state.
func (*Run) EnqueueApply ¶
func (*Run) EnqueuePlan ¶
EnqueuePlan enqueues a plan for the run. It also sets the run as the latest run for its workspace (speculative runs are ignored).
func (*Run) Finish ¶
Finish updates the run to reflect its plan or apply phase having finished. If a plan phase has finished and an apply should be automatically enqueued then autoapply will be set to true.
func (*Run) ForceCancelAvailableAt ¶
ForceCancelAvailableAt provides the time from which point it is permitted to forceably cancel the run. It only possible to do so when an attempt has previously been made to cancel the run non-forceably and a cool-off period has elapsed.
func (*Run) ForceCancelable ¶ added in v0.2.0
ForceCancelable determines whether run can be forceably cancelled.
func (*Run) HasChanges ¶
func (*Run) HasStarted ¶ added in v0.1.17
HasStarted is used by the running_time.tmpl partial template to determine whether to show the "elapsed time" for a run.
func (*Run) InProgress ¶ added in v0.2.0
func (*Run) IsAPISource ¶ added in v0.1.8
func (*Run) IsCLISource ¶ added in v0.1.8
func (*Run) IsGithubSource ¶ added in v0.1.8
func (*Run) IsGitlabSource ¶ added in v0.1.8
func (*Run) IsUISource ¶ added in v0.1.8
func (*Run) PeriodReport ¶ added in v0.1.17
func (r *Run) PeriodReport(now time.Time) (report PeriodReport)
PeriodReport provides a report of the duration in which a run has been in each status thus far. Completed statuses such as completed, errored, etc, are ignored because they are an instant not a period of time.
type Service ¶
func NewService ¶
func (*Service) AddHandlers ¶ added in v0.2.2
func (*Service) AfterCancelRun ¶ added in v0.2.0
func (*Service) AfterEnqueueApply ¶ added in v0.2.0
func (*Service) AfterEnqueuePlan ¶ added in v0.2.0
func (*Service) AfterForceCancelRun ¶ added in v0.2.0
func (*Service) EnqueuePlan ¶
EnqueuePlan enqueues a plan for the run.
NOTE: this is an internal action, invoked by the scheduler only.
func (*Service) FinishPhase ¶
func (s *Service) FinishPhase(ctx context.Context, runID resource.ID, phase internal.PhaseType, opts PhaseFinishOptions) (*Run, error)
FinishPhase finishes a phase. Creates a report of changes before updating the status of the run.
func (*Service) ForceCancel ¶ added in v0.2.2
ForceCancel forcefully cancels a run.
func (*Service) GetLockFile ¶ added in v0.2.2
GetLockFile returns the lock file for the run.
func (*Service) GetPlanFile ¶
func (s *Service) GetPlanFile(ctx context.Context, runID resource.ID, format PlanFormat) ([]byte, error)
GetPlanFile returns the plan file for the run.
func (*Service) List ¶ added in v0.2.2
List retrieves multiple runs. Use opts to filter and paginate the list.
func (Service) NewRun ¶ added in v0.2.2
func (f Service) NewRun(ctx context.Context, workspaceID resource.ID, opts CreateOptions) (*Run, error)
NewRun constructs a new run using the provided options.
func (*Service) StartPhase ¶
func (s *Service) StartPhase(ctx context.Context, runID resource.ID, phase internal.PhaseType, _ PhaseStartOptions) (*Run, error)
StartPhase starts a run phase.
func (*Service) UploadLockFile ¶ added in v0.2.2
UploadLockFile persists the lock file for a run.
func (*Service) UploadPlanFile ¶
func (s *Service) UploadPlanFile(ctx context.Context, runID resource.ID, plan []byte, format PlanFormat) error
UploadPlanFile persists a run's plan file. The plan format should be either be binary or json.
type Status ¶ added in v0.1.17
type Status string
Status represents a run state.
const ( // List all available run statuses supported in OTF. RunApplied Status = "applied" RunApplyQueued Status = "apply_queued" RunApplying Status = "applying" RunCanceled Status = "canceled" RunForceCanceled Status = "force_canceled" RunConfirmed Status = "confirmed" RunDiscarded Status = "discarded" RunErrored Status = "errored" RunPending Status = "pending" RunPlanQueued Status = "plan_queued" RunPlanned Status = "planned" RunPlannedAndFinished Status = "planned_and_finished" RunPlanning Status = "planning" // OTF doesn't support cost estimation but go-tfe API tests expect this // status so it is included expressly to pass the tests. RunCostEstimated Status = "cost_estimated" )
type StatusPeriod ¶ added in v0.1.17
StatusPeriod is the duration over which a run has had a status.
type StatusTimestamp ¶ added in v0.1.8
type Timeout ¶ added in v0.3.0
type Timeout struct { logr.Logger OverrideCheckInterval time.Duration PlanningTimeout time.Duration ApplyingTimeout time.Duration Runs timeoutRunClient }
Timeout is a daemon that "times out" runs if one of the phases - planning, applying - exceeds a timeout. This can happen for a number of reasons, for example a terraform plan or apply is stuck talking to an unresponsive API, or if OTF itself has terminated ungracefully and left runs in a planning or applying state.
type VCSProviderService ¶
type VCSProviderService vcsprovider.Service
type WatchOptions ¶
type WatchOptions struct { Organization *string `schema:"organization_name,omitempty"` // filter by organization name WorkspaceID *resource.ID `schema:"workspace_id,omitempty"` // filter by workspace ID; mutually exclusive with organization filter }
WatchOptions filters events returned by the Watch endpoint.