Skip to content

Manage several hosts

One CUE repository can describe several hosts: one package per host, shared templates in packages of their own, and a root package that collects all hosts. Each host package includes the templates it deploys by importing them.

This guide starts from a repository with SOPS set up as in Set up SOPS in a CUE repository, with the module example.com/infra@v0.

Create a directory per host

Create a directory for each host and for the shared template, and move the existing secret files to the host they belong to:

Bash
mkdir -p hosts/web01 hosts/web02 common/site
git mv creds-*.enc.yaml hosts/web01/

At the end of this guide, the repository looks like this:

Text Only
infra/
├── cue.mod/
├── .sops.yaml          # generated by cue cmd sopsgen
├── syslet.cue          # schema and output per host
├── syslet_tool.cue     # cue cmd plan / apply -t host=<name>, sopsgen
├── hosts.cue           # list of all hosts
├── sops.cue            # admin keys and .sops.yaml content
├── common/
│   └── site/
│       └── site.cue    # template shared between hosts
└── hosts/
    ├── web01/
    │   ├── host.cue
    │   └── creds-site.enc.yaml
    └── web02/
        └── host.cue

The root files use package syslet. Every other directory is its own package, named after the directory, such as package web01 or package site.

Turn syslet.cue into a host schema

Replace fqdn and sysdef with a #Host definition, so every host gets the same schema, secret loading and rendered spec:

syslet.cue
package syslet

import (
    sysletcore "github.com/xchangeee/syslet/schema/core"
    syslettools "github.com/xchangeee/syslet/schema/tools"
)

// Schema and defaults that every host's sysdef has to satisfy
#Sysdef: {
    sysletcore.#Sysdef
    sysletcore.#SysdefDefaults
}

// All settings of one host, see hosts.cue
#Host: {
    // Host that cue cmd plan/apply deploy to
    fqdn!: string

    // age public key of the host, see sops.cue
    agekey!: #AgeKey

    // SOPS-encrypted secret files of the host, keyed by file name
    secretFiles?: [string]: string

    sysdef!: #Sysdef
    if secretFiles != _|_ {
        sysdef: secrets: (syslettools.#SysdefSecretsFromEmbeddedFiles & {in: secretFiles}).secrets
    }

    // Rendered spec that cue cmd plan/apply pass to syslet
    specRendered: (syslettools.#SysletJsonFromSysdef & {in: sysdef}).specRendered
}

hosts: [string]: #Host

The secret files are no longer embedded here, since @embed reads files relative to the file it's in; each host package embeds its own.

Write a shared template

Put what several hosts deploy into a definition in its own package. It takes its settings in in and returns a sysdef fragment in out, so hosts change the settings without knowing the fragment's structure:

common/site/site.cue
package site

// nginx site shared by all web hosts.
// A host includes it in its sysdef with (site.#Sysdef & {in: {...}}).out
#Sysdef: {
    in: {
        image: string | *"docker.io/library/nginx:1.27"
        port:  int | *8080
    }
    out: containers: site: spec: unit: Container: {
        Image: in.image
        PublishPort: ["\(in.port):80"]
    }
}

Note

If you squint, this looks a lot like a Helm chart: settings go in, resources come out. With CUE modules, you can even publish such definitions and reuse them across repositories, but that's out of scope here.

Describe each host

Each host package sets the host's address and key, imports the templates it needs, and includes their out in its sysdef:

hosts/web01/host.cue
@extern(embed)

package web01

import "example.com/infra/common/site"

fqdn: "web01.example.com"

// age public key of the host
agekey: "age1..."

secretFiles: _ @embed(glob=creds-*.enc.yaml,type=text,allowEmptyGlob)

sysdef: {
    (site.#Sysdef & {in: {}}).out
}
hosts/web02/host.cue
package web02

import "example.com/infra/common/site"

fqdn: "web02.example.com"

// age public key of the host
agekey: "age1..."

sysdef: {
    (site.#Sysdef & {in: {
        image: "docker.io/library/nginx:1.28"
    }}).out
}

Get each agekey from the host's SSH host key, as in Set up SOPS in a CUE repository.

Anything that only one host deploys goes into sysdef of that host directly, next to the includes, or into further files of the host package.

List the hosts

Import every host package at the root and add it to hosts:

hosts.cue
1
2
3
4
5
6
7
8
9
package syslet

import (
    hostweb01 "example.com/infra/hosts/web01"
    hostweb02 "example.com/infra/hosts/web02"
)

hosts: web01: hostweb01
hosts: web02: hostweb02

A host package only gets checked against #Host once it's listed here. Since #Host is closed, every regular field of a host package has to be one of its fields; keep helper values in hidden fields such as _ports.

Describe the SOPS rules

Instead of editing .sops.yaml by hand, list the admin keys in CUE and derive one creation rule per host, so a host only decrypts its own secrets:

sops.cue
package syslet

import "encoding/yaml"

// age public key of an admin or a host
#AgeKey: =~"^age1"

// age public keys of all admins; every admin can decrypt the secrets of every host
sops: admins: [string]: #AgeKey
sops: admins: alice: "age1..." // your admin key

// Content of .sops.yaml, written by cue cmd sopsgen: one creation rule per
// host, so the secrets in hosts/<name>/ can be decrypted by all admins and
// that host only. Host names in hosts.cue must match their directory names.
sopsYaml: "# generated by cue cmd sopsgen, do not edit\n" + yaml.Marshal({
    creation_rules: [
        for name, host in hosts {
            path_regex: #"^hosts/\#(name)/.*\.enc\.yaml$"#
            key_groups: [{age: [for _, key in sops.admins {key}, host.agekey]}]
        },
    ]
})

Select the host in the commands

Let plan and apply take the host name from a tag, and let sopsgen write .sops.yaml:

syslet_tool.cue
package syslet

import (
    "strings"
    "tool/cli"
    "tool/exec"
    "tool/file"
)

// Resolves the host named by -t host=<name>; fails before any task runs if
// the tag is missing or names no host.
#TargetHost: {
    X1="in": string
    let Names = strings.Join([for k, _ in hosts {k}], ", ")
    out: {
        if X1 == "" {error("missing tag, use -t host=<\(Names)>")}
        if X1 != "" && hosts[X1] == _|_ {error("unknown host \"\(X1)\", use -t host=<\(Names)>")}
        if hosts[X1] != _|_ {hosts[X1]}
    }
}

// Usage: cue cmd plan -t host=<name>
command: plan: {
    hostName:   *"" | string @tag(host)
    targetHost: (#TargetHost & {in: hostName}).out

    runDeploy: exec.Run & {
        cmd: ["ssh", targetHost.fqdn, "syslet", "--stdin", "--diff"]
        stdin:  targetHost.specRendered
        stdout: string
    }
    show: cli.Print & {
        text: runDeploy.stdout
    }
}

// Usage: cue cmd apply -t host=<name>
command: apply: {
    hostName:   *"" | string @tag(host)
    targetHost: (#TargetHost & {in: hostName}).out

    runDeploy: exec.Run & {
        cmd: ["ssh", targetHost.fqdn, "syslet", "--stdin", "--diff"]
        stdin:  targetHost.specRendered
        stdout: string
    }
    showDiff: cli.Print & {
        text: runDeploy.stdout
    }
    maybeContinue: {
        if !strings.Contains(runDeploy.stdout, "No changes detected.") {
            askConfirm: cli.Ask & {
                $after:   showDiff
                prompt:   "Continue? (yes/no)"
                response: string
            }
            continue: {
                if askConfirm.response == "yes" {
                    runApply: exec.Run & {
                        cmd: ["ssh", targetHost.fqdn, "syslet", "--stdin"]
                        stdin:  targetHost.specRendered
                        stdout: string
                    }
                }
            }
        }
    }
}

// Usage: cue cmd sopsgen
// Writes .sops.yaml from the admin keys in sops.cue and the agekey of each host
command: sopsgen: {
    write: file.Create & {
        filename: ".sops.yaml"
        contents: sopsYaml
    }
}

Generate .sops.yaml

Replace the hand-written .sops.yaml with the generated one:

Bash
cue cmd sopsgen
.sops.yaml
# generated by cue cmd sopsgen, do not edit
creation_rules:
  - path_regex: ^hosts/web01/.*\.enc\.yaml$
    key_groups:
      - age:
          - age1...
          - age1...
  - path_regex: ^hosts/web02/.*\.enc\.yaml$
    key_groups:
      - age:
          - age1...
          - age1...

Commit the file, since sops reads it from the repository when you encrypt or edit a secret.

The moved secret files are still encrypted to the recipients of the old rule; re-encrypt them to the new ones:

Bash
sops updatekeys hosts/web01/*.enc.yaml

Plan and apply per host

Run the commands from the repository root and pass the host name:

Bash
1
2
3
cue cmd plan -t host=web01
cue cmd apply -t host=web01
cue vet -c ./...

Without a host name, cue cmd plan fails before it connects anywhere, so it can't deploy to the wrong host by accident:

Text Only
command.plan.targetHost: missing tag, use -t host=<web01, web02>

With GitOps, export the host's spec in the deploy script:

Bash
cue export -e hosts.web01.specRendered --out text > "$SPEC_FILE"

Add a host or an admin

Add the host to hosts.cue, or the admin key to sops: admins in sops.cue, then regenerate .sops.yaml:

Bash
cue cmd sopsgen

A new admin can't decrypt existing secrets yet: re-encrypt them with sops updatekeys (see Add a SOPS recipient).