ascode

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 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 ascode is the configuration-as-code engine shared by `wtctl apply|diff|export` and the Terraform provider: manifests of kind X named N in project P map onto the project REST API.

Index

Constants

View Source
const (
	DriftCreate = "create" // in the file, missing live
	DriftUpdate = "update" // live differs from the file (a UI edit, or a pending push)
	DriftOrphan = "orphan" // live, of a kind in the file, but not in the file: reported, never deleted
)

Drift ops reported for a manifest.

View Source
const (
	OpCreate = "create"
	OpUpdate = "update"
	OpDelete = "delete"
	OpNoop   = "noop"
	OpApply  = "apply" // RuleGroup: the API cannot list, so only the PUT reveals whether anything changed
)

Operations of a Change.

View Source
const APIVersion = "watchtower.dev/v1"

APIVersion is the only manifest apiVersion.

View Source
const ManagedBy0 = "wtctl"

ManagedBy0 is the manager name wtctl sends in X-WT-Managed-By.

View Source
const ManagedByKey = "managed-by"

ManagedByKey is the label every manifest-managed object carries.

View Source
const MaxDiffLines = 200

MaxDiffLines caps a rendered spec diff (a pull request body stays readable).

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is a 404 from the API.

View Source
var Kinds = []*Kind{

	{Name: "Environment", Path: "environments", CreateOnly: true},
	{Name: "IngestKey", Path: "credentials", CreateOnly: true,
		Refs: []Ref{{From: "env", To: "env_id", Kind: "Environment"}}, LocalFields: []string{"write_token_to", "token_env"}},
	{Name: "PublishableKey", Path: "rum/keys", Update: "PATCH", UpdateOmit: []string{"env_id"},
		Refs: []Ref{{From: "env", To: "env_id", Kind: "Environment"}}, LocalFields: []string{"write_token_to", "token_env"},
		ExportOmit: []string{"key", "snippet", "rejected_total", "rejected_origins"}},

	{Name: "Project", Path: "/v1/orgs/{org}/projects", Key: "slug", Org: true, CreateOnly: true, NoPrune: true, NoDelete: true},

	{Name: "ApiKey", Path: "/v1/orgs/{org}/api-keys", Org: true, CreateOnly: true, NoPrune: true, LocalFields: []string{"write_token_to", "token_env"}},

	{Name: "Team", Path: "/v1/orgs/{org}/teams", Org: true, CreateOnly: true, NoDelete: true, NoPrune: true},

	{Name: "CiSource", Path: "ci-sources", Key: "repo", CreateOnly: true, SecretOut: "secret", LocalFields: []string{"write_token_to", "token_env"}},
	{Name: "RedactionDetectors", Path: "redaction/detectors", Singleton: true, NoPrune: true},

	{Name: "ContactMethod", Path: "me/contact-methods", Key: "label", CreateOnly: true},
	{Name: "NotificationRule", Path: "me/notification-rules", NoPrune: true,
		Refs: []Ref{{From: "rules[].contact_method", To: "rules[].contact_method_id", Kind: "ContactMethod"}},
		// contains filtered or unexported fields
	},
	{Name: "Template", Path: "templates", Update: "PATCH"},

	{Name: "Schedule", Path: "oncall/schedules"},
	{Name: "EscalationPolicy", Path: "escalation-policies"},
	{Name: "Receiver", Path: "receivers", SecretFields: []string{"secrets"}, ExportOmit: []string{"last_delivery"},
		Refs: []Ref{{From: "config.policy", To: "config.policy_id", Kind: "EscalationPolicy"}}},
	{Name: "TimeInterval", Path: "time-intervals", UpdateOmit: []string{"name"}},
	{Name: "Routing", Path: "routing", Singleton: true, NoPrune: true,
		Refs: []Ref{{From: "receiver", Kind: "Receiver", Tree: "routes"}}},
	{Name: "InhibitRule", Path: "inhibit-rules"},
	{Name: "AlertRule", Path: "alert-rules", Refs: []Ref{{From: "env", To: "env_id", Kind: "Environment"}}},

	{Name: "SecurityRule", Path: "security/rules", Update: "PATCH"},
	{Name: "RuleGroup", Path: "rule-groups", ByName: true, NoList: true, NoPrune: true},
	{Name: "LokiRuleGroup", Path: "loki/api/v1/rules", /* contains filtered or unexported fields */},
	{Name: "MaintenanceWindow", Path: "maintenance-windows"},
	{Name: "Silence", Path: "silences", Key: "comment"},
	{Name: "Monitor", Path: "monitors", ExportOmit: []string{"last_run_at", "rule_id"}, Refs: []Ref{{From: "env", To: "env_id", Kind: "Environment"}}},
	{Name: "Slo", Path: "slos", Refs: []Ref{
		{From: "env", To: "env_id", Kind: "Environment"},
		{From: "sli.availability.monitor", Kind: "Monitor"},
		{From: "sli.monitor_state.rule", Kind: "AlertRule"},
	}},

	{Name: "QualityGate", Path: "quality-gates", CreateOnly: true, Refs: []Ref{{From: "env", To: "env_id", Kind: "Environment"}}},
	{Name: "CheckSecret", Path: "check-secrets", ByName: true, CreateOnly: true, SecretFields: []string{"value"}},
	{Name: "IncidentType", Path: "incident-types"},
	{Name: "Workflow", Path: "workflows"},
	{Name: "Dashboard", Path: "dashboards", Key: "title", Versioned: true, UpdateOmit: []string{"kind"}},
	{Name: "ServiceCatalog", Path: "catalog/services", Key: "service", ByName: true, NoPrune: true},
	{Name: "AgentConfig", Path: "agent-configs"},
	{Name: "Pipeline", Path: "pipelines", /* contains filtered or unexported fields */},

	{Name: "ShapingRule", Path: "shaping-rules", /* contains filtered or unexported fields */},
	{Name: "AttributeRegistry", Path: "attribute-registry", Key: "key", Update: "PATCH", UpdateOmit: []string{"signal", "key"}},
	{Name: "ArchiveConfig", Path: "archive", ByName: true, NoList: true, NoPrune: true, NoBodyName: true, SecretFields: []string{"credentials"}},
	{Name: "FleetConfig", Path: "fleet/configs", CreateOnly: true},
	{Name: "RetentionRule", Path: "retention-rules", Key: "priority", IntKey: true},
	{Name: "ChangeSource", Path: "change-sources", Key: "kind", Update: "PATCH", UpdateOmit: []string{"kind"}, SecretOut: "secret", LocalFields: []string{"write_token_to", "token_env"}},

	{Name: "ExportSchedule", Path: "export-schedules", Key: "signal", Update: "PATCH",
		UpdateOmit: []string{"signal", "dest_kind", "format"}, SecretFields: []string{"credentials"}},
	{Name: "IpAllowlist", Path: "/v1/orgs/{org}/ip-allowlists", Org: true, ByName: true, NoList: true, NoPrune: true, NoBodyName: true,
		ResetOnDelete: map[string]any{"cidrs": []string{}, "enabled": false}},
	{Name: "OrgSso", Path: "/v1/orgs/{org}/sso", Org: true, Singleton: true, NoPrune: true},
	{Name: "SecretStore", Path: "/v1/orgs/{org}/secret-stores", Org: true, CreateOnly: true, SecretFields: []string{"credential"}},
	{Name: "HealthToken", Path: "health-tokens", CreateOnly: true, LocalFields: []string{"write_token_to", "token_env"}},

	{Name: "ServiceAccount", Path: "/v1/orgs/{org}/service-accounts", Org: true, CreateOnly: true, NoPrune: true},

	{Name: "RepoLink", Path: "repo-links", Key: "service", ByName: true, NoBodyName: true},

	{Name: "TeamMembers", Path: "team-members", Org: true, NoList: true, NoPrune: true, NoDelete: true,
		Refs: []Ref{{From: "team", To: "team_id", Kind: "Team"}},
		// contains filtered or unexported fields
	},
}

Kinds lists every supported resource kind, in apply order.

View Source
var LookupEnv = os.LookupEnv

LookupEnv resolves ${ENV} references; tests and the Terraform provider may swap it.

Functions

func CheckAlertStages

func CheckAlertStages(cfg any) error

CheckAlertStages rejects a malformed `alert` stage (PIP-015) of a pipeline config, top level or inside v2 groups, before anything is sent; the error names the stage's JSON pointer. The API validates every stage again.

func Count

func Count(plan []Change) (n int)

Count returns how many steps write something.

func Drift

func Drift(k *Kind, spec, live map[string]any) []string

Drift is the Terraform view of Plan: the changed fields of one spec against the live body.

func ExpandSecrets

func ExpandSecrets(k *Kind, spec map[string]any) (map[string]any, error)

ExpandSecrets returns a copy of spec with its secret references replaced by environment values.

func KindNames

func KindNames() []string

KindNames is the sorted list of kind names.

func ManagedBy

func ManagedBy(repo, path string) string

ManagedBy is the label value for objects created from repo's file at path.

func Marshal

func Marshal(docs []Doc) ([]byte, error)

Marshal renders manifests as a multi-document YAML stream.

func Project

func Project(spec, live map[string]any) map[string]any

Project returns live restricted to the keys of spec (recursively), so a stored spec string can be refreshed without growing server-side fields.

func RenderSpecDiff

func RenderSpecDiff(kind, name string, lines []string) string

RenderSpecDiff is the Markdown block for a pull request body or comment.

func ShowOnce

func ShowOnce(w io.Writer, kind, name string, out map[string]any)

ShowOnce prints the secrets of a create response to w; they are never stored or shown again.

func SpecDiff

func SpecDiff(old, cur map[string]any) []string

SpecDiff is the semantic difference of two specs: one line per changed leaf, with list items compared by position and named by their `title` (panels) or `name` when they have one, so a reviewer reads "panels[2 "Latency"].targets[0].expr: ... -> ..." instead of a YAML text diff.

func Summary

func Summary(plan []Change) string

Summary renders a plan for humans, ending with a count line.

Types

type Change

type Change struct {
	Op     string
	Kind   string
	Name   string
	Fields []string // "field: live -> wanted" lines for updates
	// contains filtered or unexported fields
}

Change is one planned (or applied) step.

func (Change) Changed

func (c Change) Changed() bool

Changed reports whether the step is known to write something (a RuleGroup is resolved by its PUT).

func (Change) String

func (c Change) String() string

type Client

type Client struct {
	API     *wtapi.Client
	Project string
	Org     string // set for org-scoped kinds (NewOrg)
	// ManagedBy goes with every request as X-WT-Managed-By: the API locks what it manages (A31).
	ManagedBy string
	// PruneUnmanaged lets Plan's prune delete live resources whose read DTO does not say they
	// are managed by wtctl; otherwise those are left alone and listed in Unmanaged.
	PruneUnmanaged bool
	Unmanaged      []string // "Kind/name" kept by the last prune because no marker proved wtctl owns it
	// contains filtered or unexported fields
}

Client talks to one project through the generated wtapi client's server URL, auth and transport.

func New

func New(api, key, project string, hc *http.Client) (*Client, error)

New builds a client; hc may be nil for http.DefaultClient.

func NewOrg

func NewOrg(api, key, org string, hc *http.Client) (*Client, error)

NewOrg builds a client for the org-scoped kinds (IP allowlists, SSO, secret stores).

func NewOrgFromKey added in v0.3.2

func NewOrgFromKey(ctx context.Context, api, key, org string, hc *http.Client) (*Client, error)

NewOrgFromKey is NewOrg for a caller that has no org id: it asks the API which org the key belongs to (`GET /v1/auth/key`, which needs no scope) unless org is given.

func (*Client) Apply

func (c *Client) Apply(ctx context.Context, plan []Change, dry bool, secrets io.Writer) ([]Change, error)

Apply executes a plan. Secrets the API shows once (health token, generated webhook secret) go to secrets. With dry set nothing is written. It returns the plan with RuleGroup steps resolved.

func (*Client) ApplyManifest

func (c *Client) ApplyManifest(ctx context.Context, m *Manifest, plan []Change, secrets io.Writer) ([]Change, error)

ApplyManifest writes the creates and updates of plan. Deletes are dropped (orphans are only reported) and a step of a kind the file does not name is refused.

func (*Client) Create

func (c *Client) Create(ctx context.Context, k *Kind, name string, spec map[string]any) (map[string]any, error)

Create sends a new resource and returns the API's answer (it may carry a secret shown once).

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, k *Kind, it Item) error

Delete removes the resource.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, rel string, hdr map[string]string, body, out any) error

Do sends one request below the project path with extra headers (If-Match, Content-Type); out may be nil.

func (*Client) Export

func (c *Client) Export(ctx context.Context, kinds []string) ([]Doc, error)

Export reads the live resources of the kinds (all when empty) as manifests. Secret fields become ${ENV} references; values are never read or written.

func (*Client) Get

func (c *Client) Get(ctx context.Context, k *Kind, name string) (Item, error)

Get fetches one resource by name; ErrNotFound when absent.

func (*Client) List

func (c *Client) List(ctx context.Context, k *Kind) (map[string]Item, error)

List returns every live resource of the kind keyed by name. A Singleton yields one item named "".

func (*Client) Plan

func (c *Client) Plan(ctx context.Context, docs []Doc, prune bool) ([]Change, error)

Plan compares the manifests with the live project. With prune, live resources of the manifests' kinds that no manifest names are planned for deletion.

func (*Client) PlanManifest

func (c *Client) PlanManifest(ctx context.Context, m *Manifest) ([]Change, error)

PlanManifest plans m against the live project. Orphans are discovered with prune but turned into DriftOrphan items by Drifts; they are never part of what ApplyManifest writes.

func (*Client) Scope

func (c *Client) Scope() string

Scope is the project id, or the org id for a client made by NewOrg.

func (*Client) Update

func (c *Client) Update(ctx context.Context, k *Kind, it Item, name string, spec map[string]any) (map[string]any, error)

Update replaces the resource at it.

type DashboardSpec

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

DashboardSpec accumulates variables and panels.

func NewDashboard

func NewDashboard() *DashboardSpec

NewDashboard starts an empty spec.

func (*DashboardSpec) Build

func (d *DashboardSpec) Build() ([]byte, error)

Build returns the spec as JSON. It refuses duplicate ids and names, unknown parents and widths over 24; everything else is the server's to judge.

func (*DashboardSpec) Logs

func (d *DashboardSpec) Logs(id, title, search string, w, h int) *DashboardSpec

Logs adds a log search panel.

func (*DashboardSpec) Stat

func (d *DashboardSpec) Stat(id, title, promql string, w, h int) *DashboardSpec

Stat adds a single-value PromQL panel.

func (*DashboardSpec) Timeseries

func (d *DashboardSpec) Timeseries(id, title, promql string, w, h int) *DashboardSpec

Timeseries adds a PromQL line chart of the given size at the next free row.

func (*DashboardSpec) Var

Var adds a variable.

type Doc

type Doc struct {
	APIVersion string         `yaml:"apiVersion" json:"apiVersion"`
	Kind       string         `yaml:"kind" json:"kind"`
	Metadata   Metadata       `yaml:"metadata" json:"metadata"`
	Spec       map[string]any `yaml:"spec" json:"spec"`
}

Doc is one manifest: kind + metadata.name identify it inside a project.

func ExportDoc

func ExportDoc(k *Kind, name string, body map[string]any) Doc

ExportDoc turns a live body into a manifest.

func LoadDocs

func LoadDocs(path string) ([]Doc, error)

LoadDocs reads a file, or every .yaml/.yml/.json file below a directory (multi-document YAML allowed).

func ParseDocs

func ParseDocs(src []byte) ([]Doc, error)

ParseDocs decodes and validates a multi-document YAML (or JSON) stream.

type DriftItem

type DriftItem struct {
	Kind   string   `json:"kind"`
	Key    string   `json:"key"`
	Op     string   `json:"op"`
	Fields []string `json:"fields,omitempty"`
}

DriftItem is one difference between a manifest and the live project.

func Drifts

func Drifts(plan []Change) []DriftItem

Drifts converts a plan into drift items (no-ops are not drift).

type Grid

type Grid struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

Grid is a position on the 24 column grid.

type Item

type Item struct {
	Ref  string // id, or the name for ByName kinds
	Name string
	Body map[string]any
	// Version is a singleton's optimistic-lock version (Routing); its PUT sends it as If-Match.
	Version string
}

Item is a live resource: its API path segment and its body.

type Kind

type Kind struct {
	Name   string // manifest kind
	Path   string // collection path
	Key    string // body field that carries metadata.name (default "name")
	Update string // method for in-place updates on the item path (default PUT)

	ByName    bool // the item path uses the name, and PUT creates (no POST, no server id)
	NoList    bool // the API cannot list; every apply is sent and the server reports "unchanged"
	Singleton bool // one document per project at Path (GET and PUT, no delete)
	// CreateOnly kinds are never updated or compared once they exist (the secret is shown once).
	CreateOnly bool
	// SecretFields are body fields (or, for a map, all its values) that may only be ${ENV} references.
	SecretFields []string
	NoPrune      bool
	// Versioned kinds list summaries only and update under optimistic locking: List fetches each
	// item for its full body, and Update sends If-Match with the live version.
	Versioned bool
	// UpdateOmit are body fields the update endpoint rejects (they are only valid on create).
	UpdateOmit []string
	// NoBodyName keeps the name out of the request body (the path carries it and the schema is closed).
	NoBodyName bool
	// Org kinds live below /v1/orgs/{org}/ (Path is absolute with an {org} placeholder; Client.Org fills it).
	Org bool
	// IntKey: Key names an integer body field (a retention rule is identified by its priority).
	IntKey bool
	// NoDelete kinds cannot be deleted through the API; removing them only forgets them.
	NoDelete bool
	// ResetOnDelete, when set, is PUT to the item instead of DELETE (an IP allowlist is reset, not removed).
	ResetOnDelete map[string]any
	// SecretOut is the response field that carries the one-time secret (default "token").
	SecretOut string
	// Refs are spec fields that name another resource and are replaced by its id on apply (B4).
	Refs []Ref
	// ExportOmit are server-owned body fields `export` leaves out of the manifest.
	ExportOmit []string
	// LocalFields are spec fields that steer wtctl only (write_token_to, token_env): never sent, never compared.
	LocalFields []string
	// contains filtered or unexported fields
}

Kind describes how one resource kind maps onto the API below /v1/projects/{prj}/.

func ByKind

func ByKind(name string) *Kind

ByKind finds a kind by manifest name.

func (*Kind) NameKey

func (k *Kind) NameKey() string

NameKey is the body field that holds the resource name.

type Manifest

type Manifest struct {
	Repo, Path string
	Docs       []Doc
}

Manifest is a parsed watchtower.yaml: the as-code kinds of one repository file.

func ParseManifest

func ParseManifest(src []byte, repo, path string) (*Manifest, error)

ParseManifest decodes a watchtower.yaml. Unknown fields beside apiVersion/kind/metadata/spec are errors (a typo must not silently drop a section); every doc is labelled managed-by.

func (*Manifest) Kinds

func (m *Manifest) Kinds() map[string]bool

Kinds is the set of kinds the file names; applying never touches any other kind.

type Metadata

type Metadata struct {
	Name   string            `yaml:"name" json:"name"`
	Labels map[string]string `yaml:"labels,omitempty" json:"labels,omitempty"`
}

Metadata names the resource.

type Panel

type Panel struct {
	ID      string         `json:"id"`
	Title   string         `json:"title"`
	Type    string         `json:"type"`
	Grid    Grid           `json:"grid"`
	Query   Query          `json:"query"`
	Options map[string]any `json:"options,omitempty"`
}

Panel is one dashboard panel.

type Query

type Query struct {
	Kind string `json:"kind"`
	Text string `json:"text"`
}

Query is a panel or variable query: kind is promql, logs, traces or sql.

type Ref added in v0.3.0

type Ref struct {
	From string // dotted path of the spec field that holds a metadata.name
	To   string // dotted path the id is written to; empty = From (replace in place)
	Kind string // kind of the target
	// Tree names the list of child nodes (`routes`) that repeat the same field, to any depth: From is
	// then a plain field of the root and of every descendant.
	Tree string
}

Ref makes one spec field a reference by name: a manifest says `env: production` and apply writes the live id of Environment/production into the body (B4). Targets applied earlier in the same run are known from their create response; others from the live listing the plan already fetched.

type Variable

type Variable struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	Label      string   `json:"label,omitempty"`
	Default    string   `json:"default,omitempty"`
	Options    []string `json:"options,omitempty"`
	Query      *Query   `json:"query,omitempty"`
	Multi      bool     `json:"multi,omitempty"`
	IncludeAll bool     `json:"include_all,omitempty"`
	DependsOn  []string `json:"depends_on,omitempty"`
	Scope      string   `json:"scope,omitempty"`
}

Variable is a dashboard variable. DependsOn names parent variables; Scope a panel id.

Directories

Path Synopsis
Package ascodetest is an in-memory Watchtower project API for the as-code tests: it follows the REST shapes of the kinds table (list pages, POST create, PUT/PATCH/DELETE by id or name).
Package ascodetest is an in-memory Watchtower project API for the as-code tests: it follows the REST shapes of the kinds table (list pages, POST create, PUT/PATCH/DELETE by id or name).

Jump to

Keyboard shortcuts

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