roles

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package roles defines reusable host configuration: typed, idempotent steps such as patching, packages, files and services, applied to instances after a plan has been reviewed and approved.

Index

Constants

View Source
const (
	StatusOK      = "ok"      // already as desired
	StatusChanged = "changed" // changed (apply) or would change (plan)
	StatusSkipped = "skipped"
	StatusReboot  = "reboot" // changed, and the host is rebooting
)

Result statuses reported by step scripts.

View Source
const RebootTimeout = 10 * time.Minute

RebootTimeout is how long a rebooted host has to come back.

View Source
const SecretPlaceholder = "SECRET"

SecretPlaceholder stands in for secrets when a role is checked without them, such as when it is saved.

View Source
const SecretPrefix = "secret."

SecretPrefix marks secrets: {{ secret.db_password }} comes from the manager's vault, or offline from KORTA_SECRET_DB_PASSWORD.

Variables

This section is empty.

Functions

func AWSRelease

func AWSRelease(os string) (distro, version string, err error)

AWSRelease splits an os value such as "Rocky Linux 9" into its canonical distribution and version, "rocky" and "9".

func Facts

func Facts(name, address string, h Host) map[string]string

Facts are the built-in variables for a host.

func ParseResult

func ParseResult(out []byte) (status, detail string, ok bool)

ParseResult reads the last KORTA_RESULT line of a step's output.

func ProvisionsAWS

func ProvisionsAWS(src string) (bool, error)

ProvisionsAWS reports whether a Markdown role creates AWS resources, which needs a Korta Enterprise manager.

func Redact

func Redact(text string, secrets []string) string

Redact replaces secret values in text, for step output and errors.

func References

func References(markdown string) ([]string, error)

References lists the variables a role uses, in order of first use.

func Render

func Render(markdown string, vars map[string]string) (string, error)

Render replaces every {{ name }} with its value. A missing variable is an error with its line number, never an empty value. Values must be single lines, so they cannot change the Markdown's structure.

func RenderFile

func RenderFile(content string, vars map[string]string) (string, error)

RenderFile renders a template file, where values may span lines, such as a TLS key from the vault.

func SampleFacts

func SampleFacts() map[string]string

SampleFacts stand in for host facts when a role is checked without a host, such as when it is saved.

func Script

func Script(role string, s Step, h Host, apply, changedBefore bool) (string, error)

Script renders the shell for one step. With apply false it only reports what would change. changedBefore tells a service step whether an earlier step changed this host, for restartOnChange.

func SecretEnv

func SecretEnv(name string) string

SecretEnv is the environment variable that holds a secret offline.

func SecretRefs

func SecretRefs(markdown string, files map[string]string) []string

SecretRefs lists the secrets a role uses, by name without the prefix.

func Sources

func Sources(markdown string) ([]string, error)

Sources lists the template files a role's Files bullets name with "from", which are sent along with the role.

func StepName

func StepName(s Step) string

StepName is the step's name, or a description when it has none.

func ToMarkdown

func ToMarkdown(steps []Step) string

ToMarkdown writes steps as a Markdown role that compiles back to the same steps (step names come from the bullets).

func Variables

func Variables(markdown string) (map[string]string, error)

Variables reads the defaults in the role's # Variables section.

func WaitForHost

func WaitForHost(ctx context.Context, run Runner) error

WaitForHost waits for a rebooting host to accept commands again.

Types

type AWSInstance

type AWSInstance struct {
	Name           string   `json:"name"`
	Count          int      `json:"count,omitempty"`   // instances name, name-2 ... name-N
	OS             string   `json:"os,omitempty"`      // such as "ubuntu 24.04"
	Network        string   `json:"network,omitempty"` // a network an admin defined on the manager
	Region         string   `json:"region"`
	Image          string   `json:"image"`
	InstanceType   string   `json:"instanceType"`
	Subnet         string   `json:"subnet"`
	SecurityGroups []string `json:"securityGroups"`
	KeyPair        string   `json:"keyPair"`
	SSHKey         string   `json:"sshKey"` // vault key ID matching KeyPair
	User           string   `json:"user"`
	Address        string   `json:"address"` // public or private; empty uses the network's, or public
	// StaticIP gives each public instance an Elastic IP that survives stop
	// and start, for DNS and allow-lists. It can be switched on or off later.
	StaticIP bool `json:"staticIP,omitempty"`
	// LoadBalancer comes from the "# AWS load balancer" section.
	LoadBalancer *AWSLoadBalancer `json:"loadBalancer,omitempty"`
	// DNS names from the "# AWS DNS" section point at the load balancer, or
	// at the instances' addresses.
	DNS []string `json:"dns,omitempty"`
}

AWSInstance describes the EC2 instances a role creates. Only Name is required: the manager picks the official image for OS, the login user, the network, a security group and an SSH key. The other fields override those choices for accounts that manage their own resources. Credentials belong to the manager's AWS credential chain, never to a role.

func ParseAWS

func ParseAWS(src string) (*AWSInstance, error)

ParseAWS reads the literal provisioning section before variables are rendered. Cloud settings cannot depend on secrets or on facts from a host not yet created.

func (AWSInstance) InstanceNames

func (a AWSInstance) InstanceNames() []string

InstanceNames lists the instances the step creates, in order: name, then name-2 to name-N, so raising count from 1 keeps the first instance.

type AWSLoadBalancer

type AWSLoadBalancer struct {
	Listen      string   `json:"listen"`                // http or https
	Certificate string   `json:"certificate,omitempty"` // ACM certificate ARN, or "auto", for https
	Forward     int      `json:"forward"`               // the instances' port
	HealthCheck string   `json:"healthCheck"`           // path answered with 200-399
	From        []string `json:"from"`                  // networks that may reach it
	Internal    bool     `json:"internal,omitempty"`    // only reachable inside the VPC
}

AWSLoadBalancer puts an Application Load Balancer in front of a role's instances. Korta creates it with its target group, listeners and security group, and registers instances as count grows. It can be added, changed or removed after the instances exist.

func (AWSLoadBalancer) Ports

func (lb AWSLoadBalancer) Ports() []int

Ports are the load balancer's listener ports: 443 and 80 (which redirects) for https, 80 for http.

type AWSNetwork

type AWSNetwork struct {
	Name    string `json:"name"`
	Region  string `json:"region,omitempty"`  // default: the account's
	Account string `json:"account,omitempty"` // an AWS account entry on the manager
	VPC     string `json:"vpc,omitempty"`     // adopt this VPC instead of creating one
	CIDR    string `json:"cidr,omitempty"`    // a new VPC's range; default 10.0.0.0/16
	Zones   int    `json:"zones"`             // availability zones; default 2
	// Subnets are CIDRs Korta creates, one per zone, or in an adopted VPC
	// also the IDs of existing subnets. Empty lists are carved from the VPC
	// range; NoPublic or NoPrivate leaves that kind out.
	PublicSubnets  []string `json:"publicSubnets,omitempty"`
	PrivateSubnets []string `json:"privateSubnets,omitempty"`
	NoPublic       bool     `json:"noPublic,omitempty"`
	NoPrivate      bool     `json:"noPrivate,omitempty"`
	// NAT gives private subnets outbound internet access: one gateway,
	// one per zone, or none.
	NAT     string   `json:"nat,omitempty"`
	SSHFrom []string `json:"sshFrom,omitempty"` // who may SSH to instances; default the manager
}

AWSNetwork describes a VPC that Korta creates, or an existing one it adopts, with public and private subnets across availability zones. Instance roles place instances in it with "network: NAME". In an adopted VPC, Korta only adds resources of its own; it never changes or deletes anything it did not create.

func ParseAWSNetwork

func ParseAWSNetwork(src string) (*AWSNetwork, error)

ParseAWSNetwork reads the literal network section before variables are rendered.

func (AWSNetwork) NATGateways

func (n AWSNetwork) NATGateways() int

NATGateways is how many NAT gateways the network runs.

type GCPInstance

type GCPInstance struct {
	Name          string `json:"name"`
	Count         int    `json:"count,omitempty"`
	Project       string `json:"project"`
	Zone          string `json:"zone"`
	MachineType   string `json:"machineType"`
	ImageProject  string `json:"imageProject"`
	ImageFamily   string `json:"imageFamily"`
	SubnetProject string `json:"subnetProject"`
	Subnet        string `json:"subnet"`
	User          string `json:"user"`
	Address       string `json:"address"`
}

GCPInstance describes Compute Engine instances and the existing subnet they use.

func ParseGCP

func ParseGCP(src string) (*GCPInstance, error)

func (GCPInstance) InstanceNames

func (g GCPInstance) InstanceNames() []string

type Host

type Host struct {
	Family  string // apt or rpm
	Distro  string
	Version string // for {{ os.version }}
	Arch    string // for {{ os.arch }}
	// Planned holds the users ("user:NAME") and groups ("group:NAME") that
	// earlier steps would create. A plan changes nothing, so later steps
	// must not fail because those accounts do not exist yet.
	Planned map[string]bool
}

Host is what step scripts need to know about a target.

type HostResult

type HostResult struct {
	InstanceID string       `json:"instanceID"`
	Instance   string       `json:"instance"`
	Status     string       `json:"status"` // ok, changed, failed, skipped
	Error      string       `json:"error,omitempty"`
	Steps      []StepResult `json:"steps"`
}

HostResult is a role's outcome on one host.

func RedactResult

func RedactResult(h HostResult, secrets []string) HostResult

RedactResult removes secret values from a host's step details and errors.

func RunHost

func RunHost(ctx context.Context, r Role, t Target, apply bool) HostResult

RunHost runs every step in order and stops at the first failure. With apply false, steps only report what they would change.

func RunHosts

func RunHosts(ctx context.Context, r Role, targets []Target, apply bool, parallel int) []HostResult

RunHosts runs the role on each target, up to parallel targets at a time, and returns the results in target order.

func (HostResult) Changed

func (h HostResult) Changed() int

Changed counts the steps that changed, or would change, the host.

type Role

type Role struct {
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Markdown    string            `json:"markdown,omitempty"`
	Files       map[string]string `json:"files,omitempty"`
	Steps       []Step            `json:"steps"`
	Targets     Targets           `json:"targets"`
	Rollout     Rollout           `json:"rollout"`
}

Role is the desired configuration. Steps run in order on every target. When Markdown is set, Steps are compiled from it, and Files holds the template files its Files bullets name with "from", by relative path.

func (Role) AWS

func (r Role) AWS() *AWSInstance

AWS returns the first step's provisioning request, or nil for host-only roles.

func (Role) AWSNetwork

func (r Role) AWSNetwork() *AWSNetwork

AWSNetwork returns a network role's network, or nil for other roles.

func (*Role) Compile

func (r *Role) Compile(vars map[string]string) error

Compile renders the role's Markdown and template files with vars, then validates it. The Markdown and Files stay templates; only Steps change.

func (Role) GCP

func (r Role) GCP() *GCPInstance

func (Role) HasCommand

func (r Role) HasCommand() bool

HasCommand reports whether approval needs the command confirmation.

func (Role) Hash

func (r Role) Hash() string

Hash identifies the exact content that was planned and approved.

func (*Role) Normalize

func (r *Role) Normalize() error

Normalize validates the role and fills defaults. Normalize validates the role and fills defaults. A Markdown role is compiled with its # Variables defaults and sample host facts, which shows its steps and catches mistakes before it runs anywhere.

func (Role) Risky

func (r Role) Risky() []string

Risky reports why a role needs extra care on approval.

type Rollout

type Rollout struct {
	BatchSize         int  `json:"batchSize"`
	ContinueOnFailure bool `json:"continueOnFailure,omitempty"`
}

Rollout applies to BatchSize hosts at a time and stops after a failed batch unless ContinueOnFailure is set.

type Run

type Run struct {
	Kind    string       `json:"kind"` // plan or apply
	RoleID  string       `json:"roleID"`
	Version int          `json:"version"`
	Hash    string       `json:"hash"`
	Hosts   []HostResult `json:"hosts"`
	Changes int          `json:"changes"`
	Failed  int          `json:"failed"`
	Risks   []string     `json:"risks,omitempty"`
}

Run is the result of a plan or an apply.

func (*Run) Add

func (r *Run) Add(h HostResult)

Add records a host's result in the run's totals.

type Runner

type Runner interface {
	Run(ctx context.Context, script string) ([]byte, error)
}

Runner runs a script as root on a host and returns its output.

type Step

type Step struct {
	GCP     *GCPInstance `json:"gcp,omitempty"`
	AWS     *AWSInstance `json:"aws,omitempty"`
	Network *AWSNetwork  `json:"network,omitempty"`
	Type    string       `json:"type"` // packages, patch, group, user, directory, file, service, sysctl, firewall, command
	Name    string       `json:"name,omitempty"`

	// SELinux
	SELinuxMode    string `json:"selinuxMode,omitempty"`
	SELinuxBoolean string `json:"selinuxBoolean,omitempty"`
	SELinuxType    string `json:"selinuxType,omitempty"`
	Recursive      bool   `json:"recursive,omitempty"`

	// scheduled jobs
	Job      string `json:"job,omitempty"`
	Schedule string `json:"schedule,omitempty"`

	// hostname and timezone
	Hostname    string   `json:"hostname,omitempty"`
	Timezone    string   `json:"timezone,omitempty"`
	Nameservers []string `json:"nameservers,omitempty"`
	NTP         *bool    `json:"ntp,omitempty"`

	// packages
	State    string   `json:"state,omitempty"` // packages: present, absent, latest; file/user: present, absent; service: started, stopped; firewall: open, closed
	Packages []string `json:"packages,omitempty"`

	// patch
	Scope   string   `json:"scope,omitempty"`  // security or all
	Reboot  string   `json:"reboot,omitempty"` // never, if-required, always
	Exclude []string `json:"exclude,omitempty"`

	// file and directory; Group is also the name of a group step
	Path    string `json:"path,omitempty"`
	Content string `json:"content,omitempty"`
	Source  string `json:"source,omitempty"` // template file the content comes from
	Raw     bool   `json:"raw,omitempty"`    // copy Source exactly, without variables
	Owner   string `json:"owner,omitempty"`
	Group   string `json:"group,omitempty"`
	Mode    string `json:"mode,omitempty"`

	// group
	System bool `json:"system,omitempty"`

	// Check validates a new file before it stays: a command run after the
	// file is in place (the old file is restored if it fails), or, with %s,
	// run on the new content before it replaces the old file.
	Check string `json:"check,omitempty"`

	// service
	Service         string `json:"service,omitempty"`
	Enabled         *bool  `json:"enabled,omitempty"`
	RestartOnChange bool   `json:"restartOnChange,omitempty"`
	ReloadOnChange  bool   `json:"reloadOnChange,omitempty"`

	// sysctl
	Settings map[string]string `json:"settings,omitempty"`

	// user
	User           string   `json:"user,omitempty"`
	Groups         []string `json:"groups,omitempty"`
	Shell          string   `json:"shell,omitempty"`
	AuthorizedKeys []string `json:"authorizedKeys,omitempty"`

	// firewall
	Port     int      `json:"port,omitempty"`
	Protocol string   `json:"protocol,omitempty"` // tcp or udp
	Sources  []string `json:"sources,omitempty"`

	// command: high-risk, needs explicit confirmation on approval
	Run     string `json:"run,omitempty"`
	Creates string `json:"creates,omitempty"` // skip when this path exists
}

Step is one typed action. Only the fields of its Type are used.

func ParseMarkdown

func ParseMarkdown(src string) ([]Step, error)

ParseMarkdown compiles a Markdown role to steps.

func (Step) Provides

func (s Step) Provides() []string

Provides reports the accounts a step creates when it changes something.

type StepResult

type StepResult struct {
	Step   int    `json:"step"`
	Name   string `json:"name"`
	Status string `json:"status"` // ok, changed, skipped, reboot, failed, not run
	Detail string `json:"detail,omitempty"`
}

StepResult is one step's outcome on one host.

type Target

type Target struct {
	ID      string
	Name    string
	Connect func(ctx context.Context) (Runner, Host, error)
	Prepare func(Host) (Role, error)
}

Target is a host a role runs on. Connect opens the connection and reports the operating system, which decides how steps run. Prepare, when set, compiles the role for this host, for roles with variables.

type Targets

type Targets struct {
	InstanceIDs []string          `json:"instanceIDs,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
}

Targets selects instances by ID, by labels (all must match), or both.

Jump to

Keyboard shortcuts

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