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
- Variables
- func CheckAlertStages(cfg any) error
- func Count(plan []Change) (n int)
- func Drift(k *Kind, spec, live map[string]any) []string
- func ExpandSecrets(k *Kind, spec map[string]any) (map[string]any, error)
- func KindNames() []string
- func ManagedBy(repo, path string) string
- func Marshal(docs []Doc) ([]byte, error)
- func Project(spec, live map[string]any) map[string]any
- func RenderSpecDiff(kind, name string, lines []string) string
- func ShowOnce(w io.Writer, kind, name string, out map[string]any)
- func SpecDiff(old, cur map[string]any) []string
- func Summary(plan []Change) string
- type Change
- type Client
- func (c *Client) Apply(ctx context.Context, plan []Change, dry bool, secrets io.Writer) ([]Change, error)
- func (c *Client) ApplyManifest(ctx context.Context, m *Manifest, plan []Change, secrets io.Writer) ([]Change, error)
- func (c *Client) Create(ctx context.Context, k *Kind, name string, spec map[string]any) (map[string]any, error)
- func (c *Client) Delete(ctx context.Context, k *Kind, it Item) error
- func (c *Client) Do(ctx context.Context, method, rel string, hdr map[string]string, body, out any) error
- func (c *Client) Export(ctx context.Context, kinds []string) ([]Doc, error)
- func (c *Client) Get(ctx context.Context, k *Kind, name string) (Item, error)
- func (c *Client) List(ctx context.Context, k *Kind) (map[string]Item, error)
- func (c *Client) Plan(ctx context.Context, docs []Doc, prune bool) ([]Change, error)
- func (c *Client) PlanManifest(ctx context.Context, m *Manifest) ([]Change, error)
- func (c *Client) Scope() string
- func (c *Client) Update(ctx context.Context, k *Kind, it Item, name string, spec map[string]any) (map[string]any, error)
- type DashboardSpec
- func (d *DashboardSpec) Build() ([]byte, error)
- func (d *DashboardSpec) Logs(id, title, search string, w, h int) *DashboardSpec
- func (d *DashboardSpec) Stat(id, title, promql string, w, h int) *DashboardSpec
- func (d *DashboardSpec) Timeseries(id, title, promql string, w, h int) *DashboardSpec
- func (d *DashboardSpec) Var(v Variable) *DashboardSpec
- type Doc
- type DriftItem
- type Grid
- type Item
- type Kind
- type Manifest
- type Metadata
- type Panel
- type Query
- type Ref
- type Variable
Constants ¶
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.
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.
const APIVersion = "watchtower.dev/v1"
APIVersion is the only manifest apiVersion.
const ManagedByKey = "managed-by"
ManagedByKey is the label every manifest-managed object carries.
const MaxDiffLines = 200
MaxDiffLines caps a rendered spec diff (a pull request body stays readable).
Variables ¶
var ErrNotFound = errors.New("not found")
ErrNotFound is a 404 from the API.
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"}}}, {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: "Receiver", Path: "receivers", SecretFields: []string{"secrets"}}, {Name: "TimeInterval", Path: "time-intervals", UpdateOmit: []string{"name"}}, {Name: "Routing", Path: "routing", Singleton: true, NoPrune: true}, {Name: "InhibitRule", Path: "inhibit-rules"}, {Name: "AlertRule", Path: "alert-rules"}, {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", 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: "CheckSecret", Path: "check-secrets", ByName: true, CreateOnly: true, SecretFields: []string{"value"}}, {Name: "Schedule", Path: "oncall/schedules"}, {Name: "EscalationPolicy", Path: "escalation-policies"}, {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: "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, NoDelete: true}, {Name: "RetentionRule", Path: "retention-rules", Key: "priority", IntKey: true}, {Name: "ChangeSource", Path: "change-sources", Key: "kind", CreateOnly: true, SecretOut: "secret"}, {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}, }
Kinds lists every supported resource kind, in apply order.
var LookupEnv = os.LookupEnv
LookupEnv resolves ${ENV} references; tests and the Terraform provider may swap it.
Functions ¶
func CheckAlertStages ¶
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 Drift ¶
Drift is the Terraform view of Plan: the changed fields of one spec against the live body.
func ExpandSecrets ¶
ExpandSecrets returns a copy of spec with its secret references replaced by environment values.
func Project ¶
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 ¶
RenderSpecDiff is the Markdown block for a pull request body or comment.
func ShowOnce ¶
ShowOnce prints the secrets of a create response to w; they are never stored or shown again.
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.
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
// contains filtered or unexported fields
}
Client talks to one project through the generated wtapi client's server URL, auth and transport.
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) 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 ¶
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) List ¶
List returns every live resource of the kind keyed by name. A Singleton yields one item named "".
func (*Client) Plan ¶
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 ¶
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.
type DashboardSpec ¶
type DashboardSpec struct {
// contains filtered or unexported fields
}
DashboardSpec accumulates variables and panels.
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 ¶
func (d *DashboardSpec) Var(v Variable) *DashboardSpec
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.
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.
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
// 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}/.
type Manifest ¶
Manifest is a parsed watchtower.yaml: the as-code kinds of one repository file.
func ParseManifest ¶
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.
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 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
}
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.
Source Files
¶
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). |