diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index 2627c24d..f61420cf 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -184,6 +184,7 @@ const USUAL = ` slots = { repo = { count = 2, memory = "4g" } location = "fsn1" ssh_source_ips = [] turbo_cache_overlay = false + connect_server = false overlay_management_url = "" iam_admins = [{ name = "alice", ssh_keys = ["ssh-ed25519 AAAA alice"] }] ssh_keys = ["key-a"]`; @@ -206,7 +207,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an const run = (...args: string[]) => tryRun('mise', ['run', 'ci-hosts', '--', ...args], dir, refused); const init = await tryRun('mise', ['run', 'ci-hosts', '--', 'init', '-input=false'], dir, env); assert.ok(init.ok, init.output); - const second = `{ slots = { delivery = { count = 1, memory = "2g" } }, server_type = "cpx52", location = "nbg1", ssh_source_ips = ["203.0.113.0/24"], turbo_cache_overlay = true, overlay_management_url = "https://overlay.example", iam_admins = [{ name = "bob", ssh_keys = ["ssh-ed25519 BBBB bob"] }], ssh_keys = ["key-b"] }`; + const second = `{ slots = { delivery = { count = 1, memory = "2g" } }, server_type = "cpx52", location = "nbg1", ssh_source_ips = ["203.0.113.0/24"], turbo_cache_overlay = true, connect_server = true, overlay_management_url = "https://overlay.example", iam_admins = [{ name = "bob", ssh_keys = ["ssh-ed25519 BBBB bob"] }], ssh_keys = ["key-b"] }`; writeHosts(dir, USUAL, ` "ci-1" = {}\n "ci-2" = ${second}`); const planned = await run('plan', '-no-color', '-input=false'); assert.ok(planned.ok, planned.output); @@ -219,6 +220,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an location: 'nbg1', ssh_source_ips: '203.0.113.0/24', turbo_cache_overlay: /turbo_cache_overlay\s+= true/, + connect_server: /connect_server\s+= true/, overlay_management_url: 'https://overlay.example', iam_admins: 'bob', ssh_keys: 'key-b', @@ -229,6 +231,7 @@ test('a host’s own value wins over the default, attribute by attribute, and an location: 'fsn1', ssh_source_ips: /ssh_source_ips\s+= \[\]/, turbo_cache_overlay: /turbo_cache_overlay\s+= false/, + connect_server: /connect_server\s+= false/, overlay_management_url: /overlay_management_url\s+= ""/, iam_admins: 'alice', ssh_keys: 'key-a', @@ -296,7 +299,13 @@ test('a host’s own value wins over the default, attribute by attribute, and an }); /** Terraform's diagnostics, wrapped and boxed, on one line. */ -const flat = (output: string): string => output.replace(/[│╷╵]/g, ' ').replace(/\s+/g, ' '); +// Terraform wraps and colours its errors, and where it wraps follows the message's length: the colour codes of the frame must not split a phrase. +const flat = (output: string): string => + output + // biome-ignore lint/suspicious/noControlCharactersInRegex: the escape that starts a colour code + .replace(/\x1B\[[0-9;]*m/g, '') + .replace(/[│╷╵]/g, ' ') + .replace(/\s+/g, ' '); /** A git repository of two tagged versions of this checkout's modules, `v1` and `v2`, which a root names as `git::file://…?ref=`. */ async function moduleRepo(dir: string): Promise { diff --git a/packages/lib/src/ciRoot.test.ts b/packages/lib/src/ciRoot.test.ts new file mode 100644 index 00000000..63edaf6e --- /dev/null +++ b/packages/lib/src/ciRoot.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { renderBundled, textOf } from './testing/bundled.ts'; + +// The root ci/ of repo-operations, rendered and run by Terraform against the +// workspace's own module and a mocked provider: no token, no network (the +// provider comes from the plugin cache `mise check` fills). What a hosts file +// born at an older version means to the root is held here, since `validate` +// does not read values. +const REPO = join(import.meta.dirname, '../../..'); +const CACHE = process.env.TF_PLUGIN_CACHE_DIR ?? join(REPO, 'node_modules/.cache/terraform-plugins'); + +const FILLED = [ + [/^ {2}iam_admins = \[\]$/m, ' iam_admins = [{ name = "alice", ssh_keys = ["ssh-ed25519 AAAA alice"] }]'], + [/^ {2}ssh_keys {3}= \[\]$/m, ' ssh_keys = ["key-a"]'], +] as const; + +// The binary the repo pins, found from the repo: a shim finds no version in a temporary directory. +const TERRAFORM = + spawnSync('mise', ['which', 'terraform'], { cwd: REPO, encoding: 'utf8' }).stdout.trim() || 'terraform'; + +let dir = ''; +let usual = ''; + +const tf = (...args: string[]) => + spawnSync(TERRAFORM, args, { + cwd: join(dir, 'ci'), + encoding: 'utf8', + env: { + ...process.env, + TF_IN_AUTOMATION: '1', + TF_CLI_CONFIG_FILE: join(dir, 'terraformrc'), + HTTP_PROXY: 'http://127.0.0.1:9', + HTTPS_PROXY: 'http://127.0.0.1:9', + }, + }); + +/** The hosts file as rendered, filled in so that the module accepts it, with `hosts`; `without` removes the lines naming an attribute. */ +function hostsFile(hosts: string, without: string[] = []): string { + let text = usual; + for (const [pattern, filled] of FILLED) text = text.replace(pattern, filled); + for (const key of without) text = text.replace(new RegExp(`^ {2}${key}\\s+=.*\\n`, 'm'), ''); + return text.replace(/^hosts = \{\}$/m, `hosts = {\n${hosts}\n}`); +} + +before(async () => { + const result = await renderBundled(['repo-operations'], { tenant: 'acme', ci_strategy: 'byom' }); + dir = mkdtempSync(join(tmpdir(), 'ci-root-')); + mkdirSync(join(dir, 'ci/tests'), { recursive: true }); + for (const name of ['main.tf', 'variables.tf', 'backend.tf', 'hosts.auto.tfvars']) + writeFileSync(join(dir, 'ci', name), textOf(result, `ci/${name}`)); + usual = textOf(result, 'ci/hosts.auto.tfvars'); + const main = readFileSync(join(dir, 'ci/main.tf'), 'utf8').replace( + /git::[^"]*\/\/terraform\/hcloud_ci_runner_host\?ref=[^"]+/, + '../terraform/hcloud_ci_runner_host', + ); + // A local module must stay inside its package: the workspace's two modules are copied beside the root. + for (const module of ['hcloud_ci_runner_host', 'ci_runner_host_user_data']) + cpSync(join(REPO, 'terraform', module), join(dir, 'terraform', module), { + recursive: true, + filter: (path) => !/\.terraform|tests/.test(path.slice(REPO.length)), + }); + writeFileSync(join(dir, 'ci/main.tf'), main); + writeFileSync( + join(dir, 'ci/tests/root.tftest.hcl'), + `mock_provider "hcloud" {} +variables { + op_service_account_token = "ops_Example-0123456789" +} + +run "settings_of_the_hosts" { + command = plan + assert { + condition = jsonencode(output.settings["ci-1"]) == jsonencode(merge(var.defaults, { connect_server = false })) + error_message = "ci-1 takes the usual values and connect_server false" + } + assert { + condition = output.settings["ci-2"].connect_server == true + error_message = "ci-2 turns the Connect server on for itself" + } +} +`, + ); + // The provider is installed from the plugin cache and nowhere else. + writeFileSync( + join(dir, 'terraformrc'), + `provider_installation {\n filesystem_mirror {\n path = "${CACHE}"\n }\n}\n`, + ); + const init = tf('init', '-input=false', '-backend=false'); + assert.equal( + init.status, + 0, + `${init.stdout}${init.stderr}\nThe provider is installed from the plugin cache, ${CACHE}, which \`mise check\` fills: run it first.`, + ); +}); + +after(() => rmSync(dir, { recursive: true, force: true })); + +const plans = (hosts: string, without: string[] = []) => { + writeFileSync(join(dir, 'ci/hosts.auto.tfvars'), hostsFile(hosts, without)); + return tf('test', '-no-color'); +}; + +const HOSTS = ' "ci-1" = {}\n "ci-2" = { connect_server = true }'; + +test('a hosts file born before connect_server existed plans, and the host takes false', () => { + const ran = plans(HOSTS, ['connect_server']); + assert.equal(ran.status, 0, ran.stdout + ran.stderr); +}); + +test('a hosts file that states connect_server = false plans the same', () => { + const ran = plans(HOSTS); + assert.equal(ran.status, 0, ran.stdout + ran.stderr); +}); + +test('a misspelt key and a null are still refused by name', () => { + const typoHost = plans(' "ci-1" = { conect_server = true }', ['connect_server']); + assert.notEqual(typoHost.status, 0); + assert.match(typoHost.stdout + typoHost.stderr, /ci-1\.conect_server/); + const nullHost = plans(' "ci-1" = { connect_server = null }', ['connect_server']); + assert.notEqual(nullHost.status, 0); + assert.match(nullHost.stdout + nullHost.stderr, /ci-1\.connect_server is null/); + writeFileSync( + join(dir, 'ci/hosts.auto.tfvars'), + hostsFile(' "ci-1" = {}', ['connect_server']).replace(/^defaults = \{/m, 'defaults = {\n conect_server = true'), + ); + const typoDefault = tf('test', '-no-color'); + assert.notEqual(typoDefault.status, 0); + assert.match(typoDefault.stdout + typoDefault.stderr, /unknown: \[conect_server\]/); + writeFileSync( + join(dir, 'ci/hosts.auto.tfvars'), + hostsFile(' "ci-1" = {}', ['connect_server']).replace(/^defaults = \{/m, 'defaults = {\n connect_server = null'), + ); + const nullDefault = tf('test', '-no-color'); + assert.notEqual(nullDefault.status, 0); + assert.match(nullDefault.stdout + nullDefault.stderr, /defaults\.connect_server is null/); +}); + +test('an attribute other than a fallback still has to be in defaults', () => { + const ran = plans(HOSTS, ['connect_server', 'location']); + assert.notEqual(ran.status, 0); + assert.match(ran.stdout + ran.stderr, /missing: \[location\]/); +}); + +test('the user-data module’s header states once the rule for a setting added later that is written only where it differs from the role’s default', () => { + const main = readFileSync(join(REPO, 'terraform/ci_runner_host_user_data/main.tf'), 'utf8'); + const header = main.slice(0, main.indexOf('locals {')); + assert.match( + header.replace(/\n# /g, ' '), + /a setting added after the module first shipped is written only where it differs from the role's default, so that taking it replaces no host.*the values from the start are always written/i, + ); + assert.match(header.replace(/\n# /g, ' '), /credentials and the token/); +}); diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index 97bd3600..87e8bade 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -296,6 +296,49 @@ test('a host is a name and what the module takes, the tenant’s usual values it assert.match(tfvars, /ci-runner-unregister/, 'a person removing an entry is told to unregister first'); }); +test('a host turns its Connect server on by connect_server, off in the usual values, and the root passes it the way it passes turbo_cache_overlay', async () => { + const result = await render({ ci_strategy: 'byom' }); + assert.match(textOf(result, 'ci/hosts.auto.tfvars'), /^ {2}connect_server\s+= false$/m); + assert.match(textOf(result, 'ci/variables.tf'), /attributes = \[[^\]]*"connect_server"/); + assert.match(textOf(result, 'ci/main.tf'), /connect_server\s+= local\.settings\[each\.key\]\.connect_server/); +}); + +test('the root’s list of attributes is the module’s inputs and no more', async () => { + const root = textOf(await render({ ci_strategy: 'byom' }), 'ci/variables.tf'); + const listed = + /attributes = \[([^\]]*)\]/ + .exec(root)?.[1] + ?.match(/"([^"]+)"/g) + ?.map((name) => name.slice(1, -1)) ?? []; + const module = readFileSync( + join(import.meta.dirname, '../../../terraform/hcloud_ci_runner_host/variables.tf'), + 'utf8', + ); + const inputs = [...module.matchAll(/^variable "(\w+)"/gm)] + .map((m) => m[1] ?? '') + .filter((name) => !['name', 'owner', 'plexus_version', 'op_service_account_token'].includes(name)); + assert.deepEqual([...listed].sort(), inputs.sort()); +}); + +test('where a tenant decides on connect_server, it says what the host then holds and what is untried', async () => { + const result = await render({ ci_strategy: 'byom' }); + const tfvars = textOf(result, 'ci/hosts.auto.tfvars'); + const above = /((?:^ {2}#.*\n)+)^ {2}connect_server\s+=/m.exec(tfvars)?.[1] ?? ''; + assert.match(above, /every slot[^\n]*(repo|delivery)[\s\S]*deploy key/i); + assert.match(above, /untried/); + const variables = textOf(result, 'ci/variables.tf'); + assert.match(variables, /connect_server[\s\S]*deploy key[\s\S]*untried/); +}); + +test('the root gives an attribute added after a hosts file was born a fallback, by one rule, and never a key that is no attribute', async () => { + const result = await render({ ci_strategy: 'byom' }); + const variables = textOf(result, 'ci/variables.tf'); + const main = textOf(result, 'ci/main.tf'); + assert.match(variables, /fallbacks\s+= \{ connect_server = false \}/); + assert.match(variables, /byte for byte/); + assert.match(main, /merge\(local\.fallbacks, var\.defaults, host\)/); +}); + test('the files hold no secret: the provider’s token and the bootstrap token are pointers, the rest names nothing of a tenant but its answers', async () => { const result = await render({ ci_strategy: 'byom' }); const secrets = textOf(result, 'ci/secrets.env') @@ -392,7 +435,7 @@ test('the hosts file and the root say which edit of defaults replaces a host, wh assert.doesNotMatch(text, /edit of `defaults` replaces every host|never updated/, path); assert.match( text, - /slots, turbo_cache_overlay, overlay_management_url or iam_admins[^\n]*or location[^\n]*replaces every host that does not set it itself/, + /slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins[^\n]*or location[^\n]*replaces every host that does not set it itself/, path, ); assert.match(text, /server_type[^\n]*resized in place, which powers the host off: power it on afterwards/, path); diff --git a/packages/lib/turbo.json b/packages/lib/turbo.json index 0f0696d1..f3f8f5f2 100644 --- a/packages/lib/turbo.json +++ b/packages/lib/turbo.json @@ -2,7 +2,7 @@ "extends": ["//"], "tasks": { "test": { - "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**"] + "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**", "../../terraform/**"] } } } diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars index c5d6cab5..98469506 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars @@ -1,5 +1,5 @@ # Born from plexus-ms/tooling, templates/repo-operations, and the tenant's: plx update never changes it. The runner hosts that exist, and the tenant's usual values. -# A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. Leaving byom removes the root's other files but not this file, the state or the hosts: destroy them first. +# A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. Leaving byom removes the root's other files but not this file, the state or the hosts: destroy them first. defaults = { slots = { repo = { count = 2, memory = "4g" } @@ -13,6 +13,8 @@ defaults = { # The people who administer a host, [{ name, ssh_keys }], and the names of the project's SSH keys that open it until the first run. iam_admins = [] ssh_keys = [] + # A 1Password Connect server of the host's own, which its slots read the CI vault through: every slot of the host, repo and delivery, then holds a token that reads the whole vault, the deploy key included. Whether one set of Connect credentials serves several hosts at once is untried. Its credentials are the item 1password-connect of the vault -ci-host. + connect_server = false } # A host is its name and what it sets differently from the defaults: hosts = { "ci-1" = {}, "ci-2" = { location = "nbg1" } } diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja index 95f7ade0..f5e88e6f 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/main.tf.jinja @@ -1,5 +1,5 @@ # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. +# One runner host per entry of `hosts` (hosts.auto.tfvars). A new Plexus version, which changes the two lines of main.tf that name it, replaces every host, and so does an edit of `defaults` to slots, turbo_cache_overlay, connect_server, overlay_management_url or iam_admins (they reach the user-data) or location, which replaces every host that does not set it itself; the plan says `must be replaced` there. A new server_type is resized in place, which powers the host off: power it on afterwards, ssh_source_ips changes the firewall in place, and ssh_keys is ignored after creation. Run `ci-runner-unregister` on a host as root before any apply that removes or replaces it, so that the forge lists none of its runners. terraform { required_providers { hcloud = { @@ -13,7 +13,7 @@ provider "hcloud" {} locals { # Each host's own values over the tenant's usual ones. - settings = { for name, host in var.hosts : name => merge(var.defaults, host) } + settings = { for name, host in var.hosts : name => merge(local.fallbacks, var.defaults, host) } } module "runner_host" { @@ -30,6 +30,7 @@ module "runner_host" { location = local.settings[each.key].location ssh_source_ips = local.settings[each.key].ssh_source_ips turbo_cache_overlay = local.settings[each.key].turbo_cache_overlay + connect_server = local.settings[each.key].connect_server overlay_management_url = local.settings[each.key].overlay_management_url iam_admins = local.settings[each.key].iam_admins ssh_keys = local.settings[each.key].ssh_keys diff --git a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf index cecbddfe..e895fa0f 100644 --- a/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf +++ b/templates/repo-operations/files/{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/variables.tf @@ -8,11 +8,14 @@ variable "op_service_account_token" { locals { # The attributes of a host, each the module's input of the same name; the module checks their types. - attributes = ["slots", "server_type", "location", "ssh_source_ips", "turbo_cache_overlay", "overlay_management_url", "iam_admins", "ssh_keys"] + attributes = ["slots", "server_type", "location", "ssh_source_ips", "turbo_cache_overlay", "connect_server", "overlay_management_url", "iam_admins", "ssh_keys"] + + # What a hosts file that lacks an attribute means by it: an attribute may get a fallback only where its fallback leaves the user-data of the hosts that exist byte for byte as it was, so that taking a version replaces none of them. A file born before the attribute existed then plans as it is; every other attribute must be in defaults. + fallbacks = { connect_server = false } } variable "defaults" { - description = "The tenant's usual values, taken by a host that names none of its own: every attribute, and no other key, and none null." + description = "The tenant's usual values, taken by a host that names none of its own: every attribute but those with a fallback, and no other key, and none null. connect_server turns on a 1Password Connect server of the host's own: every slot of the host, repo and delivery, then reads the whole CI vault through it, the deploy key included, and whether one set of Connect credentials serves several hosts at once is untried." type = any validation { @@ -21,8 +24,8 @@ variable "defaults" { } validation { - condition = can(keys(var.defaults)) ? length(setsubtract(keys(var.defaults), local.attributes)) == 0 && length(setsubtract(local.attributes, keys(var.defaults))) == 0 : true - error_message = "defaults holds exactly the attributes ${join(", ", local.attributes)}; unknown: [${join(", ", try(setsubtract(keys(var.defaults), local.attributes), []))}], missing: [${join(", ", try(setsubtract(local.attributes, keys(var.defaults)), []))}]." + condition = can(keys(var.defaults)) ? length(setsubtract(keys(var.defaults), local.attributes)) == 0 && length(setsubtract(setsubtract(local.attributes, keys(local.fallbacks)), keys(var.defaults))) == 0 : true + error_message = "defaults holds exactly the attributes ${join(", ", local.attributes)}; unknown: [${join(", ", try(setsubtract(keys(var.defaults), local.attributes), []))}], missing: [${join(", ", try(setsubtract(setsubtract(local.attributes, keys(local.fallbacks)), keys(var.defaults)), []))}]." } validation { diff --git a/terraform/ci_runner_host_user_data/main.tf b/terraform/ci_runner_host_user_data/main.tf index 55949897..e71dd610 100644 --- a/terraform/ci_runner_host_user_data/main.tf +++ b/terraform/ci_runner_host_user_data/main.tf @@ -14,9 +14,15 @@ # - installs the collections, then runs plexus.ci.playbook on the host. # # The role is the implementation: the playbook installs the vault's CLI and -# reads every other secret from the vault itself. The user-data states the +# reads every other secret from the vault itself, among them the credentials +# and the token of a Connect server (connect_server). The user-data states the # host and holds no logic. # +# A setting added after the module first shipped is written only where it +# differs from the role's default, so that taking it replaces no host: the +# overlay's management server and connect_server are in the values file when +# set and absent otherwise. The values from the start are always written. +# # The output carries the one secret, so it is sensitive, and so is the state # or plan file of a caller that keeps it. The text is a function of the # variables alone: the same variables give the same text, and a change to any @@ -30,5 +36,8 @@ locals { turbo_cache_overlay = var.turbo_cache_overlay }, var.overlay_management_url == "" ? {} : { netbird_management_url = var.overlay_management_url }, + # Named only when on, so that the text of a host without a Connect server + # is what it always was: a changed user-data is a new machine. + var.connect_server ? { actions_runners_connect = true } : {}, ) } diff --git a/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl b/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl index 668722ae..67fb87c0 100644 --- a/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl +++ b/terraform/ci_runner_host_user_data/tests/user_data.tftest.hcl @@ -98,6 +98,61 @@ run "serves_the_caches_on_the_overlay" { } } +# A host that leaves the Connect server off is the host that exists today: a +# changed user-data replaces the machine, so its text is held byte for byte +# (the hash is of the text as it was before the variable existed). +run "leaves_the_text_of_a_host_without_connect_as_it_was" { + command = plan + + assert { + condition = nonsensitive(sha256(output.user_data)) == "f7d497a15b34bca2e302326db206b044efc5d0abe39fbe90d62657588326e19f" + error_message = "The user-data of a host with the Connect server off must not change by a byte, or taking a version replaces it." + } + + assert { + condition = !contains(keys(jsondecode([for f in yamldecode(output.user_data).write_files : f.content if f.path == "/etc/plexus-ci/values.yml"][0])), "actions_runners_connect") + error_message = "With the Connect server off the values file must leave the role's default alone." + } +} + +run "turns_the_connect_server_on_as_a_boolean" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = jsondecode([for f in yamldecode(output.user_data).write_files : f.content if f.path == "/etc/plexus-ci/values.yml"][0]).actions_runners_connect == true + error_message = "actions_runners_connect must be the boolean true: the playbook refuses a string." + } + + assert { + condition = output.user_data != run.is_cloud_config.user_data + error_message = "Turning the Connect server on must reach the user-data." + } +} + +# The credentials and the access token are read from the host's vault by the +# playbook: the user-data carries the one token and nothing of Connect's. +run "carries_no_credential_of_the_connect_server" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = [for f in yamldecode(output.user_data).write_files : f.path if strcontains(f.content, var.op_service_account_token)] == ["/etc/plexus-ci/token.env"] + error_message = "The token must still be in token.env and in no other file." + } + + assert { + condition = !strcontains(output.user_data, "op://") && !strcontains(output.user_data, "1password-credentials") && !strcontains(output.user_data, "OP_CONNECT") + error_message = "No pointer, credentials file or Connect token belongs in the user-data." + } +} + run "names_the_overlays_management_server_only_when_given" { command = plan diff --git a/terraform/ci_runner_host_user_data/variables.tf b/terraform/ci_runner_host_user_data/variables.tf index 0a535549..82ce2f44 100644 --- a/terraform/ci_runner_host_user_data/variables.tf +++ b/terraform/ci_runner_host_user_data/variables.tf @@ -54,6 +54,12 @@ variable "turbo_cache_overlay" { default = false } +variable "connect_server" { + description = "Whether the host runs a 1Password Connect server of its own, which its slots read the vault -ci through. The playbook reads the credentials and the token from the item 1password-connect of the vault -ci-host. With it, a slot's token reads everything the Connect server's vault holds, the deploy key too." + type = bool + default = false +} + variable "overlay_management_url" { description = "The overlay's management server, where it is not NetBird's own; empty leaves the role's default." type = string diff --git a/terraform/hcloud_ci_runner_host/main.tf b/terraform/hcloud_ci_runner_host/main.tf index 12926633..e249a154 100644 --- a/terraform/hcloud_ci_runner_host/main.tf +++ b/terraform/hcloud_ci_runner_host/main.tf @@ -8,7 +8,8 @@ # plexus.ci at the Plexus version and runs plexus.ci.playbook on the machine # itself, with the slots and the owner as values and one secret, a service # account token for the vault -ci-host, from which the playbook reads -# the rest. The role is the implementation; the user-data holds no logic, and +# the rest, the credentials of the host's Connect server (connect_server) +# among them. The role is the implementation; the user-data holds no logic, and # is rendered by ../ci_runner_host_user_data, which a machine of another kind # can use alone. The user-data holds the token, so a plan file of the caller # does too, and the state keeps a hash of it: the module marks it sensitive, @@ -54,6 +55,7 @@ module "user_data" { plexus_version = var.plexus_version slots = var.slots turbo_cache_overlay = var.turbo_cache_overlay + connect_server = var.connect_server overlay_management_url = var.overlay_management_url iam_admins = var.iam_admins op_service_account_token = var.op_service_account_token diff --git a/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl b/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl index dd4e7e79..73a04564 100644 --- a/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl +++ b/terraform/hcloud_ci_runner_host/tests/host.tftest.hcl @@ -204,6 +204,28 @@ run "passes_the_overlay_values_to_the_user_data" { } } +run "leaves_the_connect_server_out_of_the_user_data_when_off" { + command = plan + + assert { + condition = !strcontains(nonsensitive(hcloud_server.host.user_data), "actions_runners_connect") + error_message = "A host with the Connect server off must get the user-data it always got." + } +} + +run "passes_the_connect_server_on_to_the_user_data" { + command = plan + + variables { + connect_server = true + } + + assert { + condition = strcontains(nonsensitive(hcloud_server.host.user_data), "\"actions_runners_connect\":true") + error_message = "connect_server must reach the playbook's values as actions_runners_connect." + } +} + # The keys and the image only matter when the machine is created: a later # change must not replace a machine that works. The machine of the first run # is the one the state holds. diff --git a/terraform/hcloud_ci_runner_host/variables.tf b/terraform/hcloud_ci_runner_host/variables.tf index 17fcf334..6372fbbc 100644 --- a/terraform/hcloud_ci_runner_host/variables.tf +++ b/terraform/hcloud_ci_runner_host/variables.tf @@ -24,6 +24,12 @@ variable "turbo_cache_overlay" { default = false } +variable "connect_server" { + description = "Whether the host runs a 1Password Connect server of its own, which its slots read the vault -ci through, so that their reads spend none of the service account's budget. The playbook reads the credentials and the token from the item 1password-connect of the vault -ci-host. With it, a slot's token reads everything the Connect server's vault holds, the deploy key too; whether one set of credentials serves several hosts at once is untried. A change replaces the machine." + type = bool + default = false +} + variable "overlay_management_url" { description = "The overlay's management server, where it is not NetBird's own; empty leaves the role's default." type = string