Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions newborns/repo-operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]`;
Expand All @@ -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);
Expand All @@ -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',
Expand All @@ -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',
Expand Down Expand Up @@ -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<string> {
Expand Down
157 changes: 157 additions & 0 deletions packages/lib/src/ciRoot.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
45 changes: 44 additions & 1 deletion packages/lib/src/repoOperations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion packages/lib/turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": ["//"],
"tasks": {
"test": {
"inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**"]
"inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**", "../../terraform/**"]
}
}
}
Original file line number Diff line number Diff line change
@@ -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" }
Expand All @@ -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 <owner>-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" } }
Expand Down
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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" {
Expand All @@ -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
Expand Down
Loading