From e7eee508d70fd7cc0a777b78385047890f275e9c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Mon, 9 Nov 2026 23:53:49 +1100 Subject: [PATCH 1/9] manage IUCLabs GitHub organisation --- .woodpecker/pre-commit.yaml | 1 + Makefile | 13 +- README.md | 46 +++++- config/config.hcl | 35 +++- .../IUCLabs/repository/.github.yaml | 7 + .../github.com/IUCLabs/ruleset/default.yaml | 12 ++ .../github.com/IUCLabs/team/maintainers.yaml | 5 + environments/au/syd1/terragrunt.hcl | 24 +++ environments/github/iuclabs/terragrunt.hcl | 36 +++++ environments/root.hcl | 18 --- modules/github_org/main.tf | 149 ++++++++++++++++++ modules/github_org/terraform.tf | 9 ++ .../github_org/tests/github_org.tftest.hcl | 48 ++++++ modules/github_org/variables.tf | 74 +++++++++ 14 files changed, 450 insertions(+), 27 deletions(-) create mode 100644 config/github.com/IUCLabs/repository/.github.yaml create mode 100644 config/github.com/IUCLabs/ruleset/default.yaml create mode 100644 config/github.com/IUCLabs/team/maintainers.yaml create mode 100644 environments/github/iuclabs/terragrunt.hcl create mode 100644 modules/github_org/main.tf create mode 100644 modules/github_org/terraform.tf create mode 100644 modules/github_org/tests/github_org.tftest.hcl create mode 100644 modules/github_org/variables.tf diff --git a/.woodpecker/pre-commit.yaml b/.woodpecker/pre-commit.yaml index 3f48f3c..28d8926 100644 --- a/.woodpecker/pre-commit.yaml +++ b/.woodpecker/pre-commit.yaml @@ -6,6 +6,7 @@ steps: image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/opentofu:0.1.0 commands: - uvx pre-commit run --all-files + - make test backend_options: kubernetes: serviceAccountName: default diff --git a/Makefile b/Makefile index 9be174d..813d2b4 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: init plan apply apply-if-changes format pre-commit +.PHONY: init plan apply apply-if-changes format pre-commit test VAULT_AUTH_METHOD ?= approle VAULT_K8S_ROLE ?= woodpecker_terraform_git @@ -14,7 +14,10 @@ define vault_env fi && \ export CONSUL_HTTP_TOKEN=$$(vault read -field=token consul_root/au/syd1/creds/terraform-git) && \ export GITEA_TOKEN=$$(vault kv get -field=token kv/service/gitea/gitadmin/tokens/terraform-git) && \ - export WOODPECKER_TOKEN=$$(vault kv get -field=token kv/service/woodpecker/tokens/gitadmin) + export WOODPECKER_TOKEN=$$(vault kv get -field=token kv/service/woodpecker/tokens/gitadmin) && \ + export GITHUB_APP_ID=$$(vault kv get -field=app_id kv/service/github/iuclabs/terraform) && \ + export GITHUB_APP_INSTALLATION_ID=$$(vault kv get -field=installation_id kv/service/github/iuclabs/terraform) && \ + export GITHUB_APP_PEM_FILE="$$(vault kv get -field=pem kv/service/github/iuclabs/terraform)" endef init: @@ -50,3 +53,9 @@ format: pre-commit: @uvx pre-commit run --all-files + +test: + @tofu -chdir=modules/github_org init -backend=false -input=false >/dev/null && \ + tofu -chdir=modules/github_org test + @terragrunt render --working-dir environments/au/syd1 --json --out /dev/stdout 2>/dev/null | \ + python3 -c 'import json,sys; i=json.loads(sys.stdin.read().splitlines()[-1])["inputs"]; bad=[k for m in i.values() for k in m if k.startswith("github.com/")]; sys.exit(f"github.com config in gitea inputs: {bad}" if bad else 0)' diff --git a/README.md b/README.md index 225643e..b41fbd2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,47 @@ # terraform-git -Manage Gitea resources, teams, repos, and Woodpecker CI via Terraform \ No newline at end of file +Manage Gitea resources, teams, repos, and Woodpecker CI via Terraform. + +## GitHub (IUCLabs) + +`config/github.com/IUCLabs/` feeds `modules/github_org` via `environments/github/iuclabs`, authenticated as a GitHub App (`kv/service/github/iuclabs/terraform`). Org membership invites are manual. + +`team/.yaml`: + +```yaml +description: "IUCLabs maintainers" +privacy: closed +maintainers: [neoloc] +members: [] +``` + +`ruleset/.yaml` (applied per repository; org rulesets need a paid plan): + +```yaml +target: branch +enforcement: active +conditions: + ref_name: + include: ["~DEFAULT_BRANCH"] + exclude: [] +rules: + deletion: true + non_fast_forward: true + pull_request: + required_approving_review_count: 0 + dismiss_stale_reviews_on_push: true + required_status_checks: + contexts: [ci/woodpecker] +``` + +`repository/.yaml` (squash-only, delete branch on merge, `main` by default): + +```yaml +description: "IUCLabs organisation profile" +private: false +rulesets: [default] +maintainers: ["@maintainers"] +codeowners: [] +``` + +`maintainers` (users or `@team`) get `maintain` and seed the initial `.github/CODEOWNERS`, which is then left to humans. `codeowners` get `push` so they can be added to CODEOWNERS later. Private repositories cannot use rulesets on the free plan; plan fails if they do. diff --git a/config/config.hcl b/config/config.hcl index ad99dbc..335bbd3 100644 --- a/config/config.hcl +++ b/config/config.hcl @@ -6,9 +6,24 @@ locals { file_path => yamldecode(file(file_path)) } + gitea_configs = { + for file_path, content in local.all_configs : + file_path => content if split("/", file_path)[0] != "github.com" + } + + github_configs = { + for file_path, content in local.all_configs : + file_path => merge(content, { + name = trimsuffix(basename(file_path), ".yaml") + organisation = split("/", file_path)[1] + kind = split("/", file_path)[2] + }) + if split("/", file_path)[0] == "github.com" + } + config = { organisation = { - for file_path, content in local.all_configs : + for file_path, content in local.gitea_configs : trimsuffix(replace(file_path, "/config.yaml", ""), ".yaml") => merge(content, { name = split("/", file_path)[1] gitea_url = split("/", file_path)[0] @@ -16,7 +31,7 @@ locals { if endswith(file_path, "/config.yaml") && length(split("/", file_path)) == 3 } repository = { - for file_path, content in local.all_configs : + for file_path, content in local.gitea_configs : "${split("/", file_path)[0]}/${split("/", file_path)[1]}/${trimsuffix(basename(file_path), ".yaml")}" => merge(content, { name = trimsuffix(basename(file_path), ".yaml") organisation = split("/", file_path)[1] @@ -25,7 +40,7 @@ locals { if length(regexall("/repository/", file_path)) > 0 } team = { - for file_path, content in local.all_configs : + for file_path, content in local.gitea_configs : "${split("/", file_path)[0]}/${split("/", file_path)[1]}/${trimsuffix(basename(file_path), ".yaml")}" => merge(content, { name = trimsuffix(basename(file_path), ".yaml") organisation = split("/", file_path)[1] @@ -34,7 +49,7 @@ locals { if length(regexall("/team/", file_path)) > 0 } user = { - for file_path, content in local.all_configs : + for file_path, content in local.gitea_configs : "${split("/", file_path)[0]}/${trimsuffix(basename(file_path), ".yaml")}" => merge(content, { username = trimsuffix(basename(file_path), ".yaml") gitea_url = split("/", file_path)[0] @@ -42,7 +57,7 @@ locals { if length(regexall("/user/", file_path)) > 0 } branch_protection = merge([ - for file_path, content in local.all_configs : { + for file_path, content in local.gitea_configs : { for idx, rule in try(content.branch_protection, []) : "${split("/", file_path)[0]}/${split("/", file_path)[1]}/${trimsuffix(basename(file_path), ".yaml")}/${rule.rule_name}" => merge(rule, { repository = trimsuffix(basename(file_path), ".yaml") @@ -53,7 +68,7 @@ locals { if length(regexall("/repository/", file_path)) > 0 ]...) deploy_key = { - for file_path, content in local.all_configs : + for file_path, content in local.gitea_configs : "${split("/", file_path)[0]}/${split("/", file_path)[1]}/${split("/", replace(file_path, "deploy_key/", ""))[2]}/${trimsuffix(basename(file_path), ".yaml")}" => merge(content, { title = trimsuffix(basename(file_path), ".yaml") repository = split("/", replace(file_path, "deploy_key/", ""))[2] @@ -63,4 +78,12 @@ locals { if length(regexall("/deploy_key/", file_path)) > 0 } } + + github = { + for kind in ["team", "ruleset", "repository"] : kind => { + for file_path, content in local.github_configs : + "${content.organisation}/${content.name}" => content + if content.kind == kind + } + } } diff --git a/config/github.com/IUCLabs/repository/.github.yaml b/config/github.com/IUCLabs/repository/.github.yaml new file mode 100644 index 0000000..b08224c --- /dev/null +++ b/config/github.com/IUCLabs/repository/.github.yaml @@ -0,0 +1,7 @@ +description: "IUCLabs organisation profile" +private: false +rulesets: + - default +maintainers: + - "@maintainers" +codeowners: [] diff --git a/config/github.com/IUCLabs/ruleset/default.yaml b/config/github.com/IUCLabs/ruleset/default.yaml new file mode 100644 index 0000000..1715997 --- /dev/null +++ b/config/github.com/IUCLabs/ruleset/default.yaml @@ -0,0 +1,12 @@ +target: branch +enforcement: active +conditions: + ref_name: + include: ["~DEFAULT_BRANCH"] + exclude: [] +rules: + deletion: true + non_fast_forward: true + pull_request: + required_approving_review_count: 0 + dismiss_stale_reviews_on_push: true diff --git a/config/github.com/IUCLabs/team/maintainers.yaml b/config/github.com/IUCLabs/team/maintainers.yaml new file mode 100644 index 0000000..fd406c2 --- /dev/null +++ b/config/github.com/IUCLabs/team/maintainers.yaml @@ -0,0 +1,5 @@ +description: "IUCLabs maintainers" +privacy: closed +maintainers: + - neoloc +members: [] diff --git a/environments/au/syd1/terragrunt.hcl b/environments/au/syd1/terragrunt.hcl index ab4e5da..b646885 100644 --- a/environments/au/syd1/terragrunt.hcl +++ b/environments/au/syd1/terragrunt.hcl @@ -16,6 +16,30 @@ terraform { source = "../../../modules/gitea_instance" } +generate "provider" { + path = "provider.tf" + if_exists = "overwrite" + contents = < v if v.organisation == local.owner } + ruleset = { for k, v in local.github.ruleset : v.name => v if v.organisation == local.owner } + repository = { for k, v in local.github.repository : v.name => v if v.organisation == local.owner } +} diff --git a/environments/root.hcl b/environments/root.hcl index 7413786..594d875 100644 --- a/environments/root.hcl +++ b/environments/root.hcl @@ -2,24 +2,6 @@ generate "backend" { path = "backend.tf" if_exists = "overwrite" contents = < { team = team, username = u, role = "member" } }, + { for u in t.maintainers : "${team}/${u}" => { team = team, username = u, role = "maintainer" } }, + ) + ]...) + + repository_access = { + for name, r in var.repository : name => merge( + { for e in r.codeowners : e => "push" }, + { for e in r.maintainers : e => "maintain" }, + ) + } + + repository_ruleset = merge([ + for name, r in var.repository : { + for rs in r.rulesets : "${name}/${rs}" => { repository = name, ruleset = var.ruleset[rs] } + } + ]...) +} + +resource "github_team" "this" { + for_each = var.team + + name = each.value.name + description = each.value.description + privacy = each.value.privacy +} + +resource "github_team_membership" "this" { + for_each = local.team_membership + + team_id = github_team.this[each.value.team].id + username = each.value.username + role = each.value.role +} + +resource "github_repository" "this" { + for_each = var.repository + + name = each.value.name + description = each.value.description + visibility = each.value.private ? "private" : "public" + has_issues = each.value.has_issues + has_wiki = each.value.has_wiki + has_projects = each.value.has_projects + allow_squash_merge = each.value.allow_squash_merge + allow_merge_commit = each.value.allow_merge_commit + allow_rebase_merge = each.value.allow_rebase_merge + delete_branch_on_merge = each.value.delete_branch_on_merge + auto_init = each.value.auto_init +} + +resource "github_branch_default" "this" { + for_each = var.repository + + repository = github_repository.this[each.key].name + branch = each.value.default_branch +} + +resource "github_repository_collaborators" "this" { + for_each = { for name, access in local.repository_access : name => access if length(access) > 0 } + + repository = github_repository.this[each.key].name + + dynamic "user" { + for_each = { for e, p in each.value : e => p if !startswith(e, "@") } + content { + username = user.key + permission = user.value + } + } + + dynamic "team" { + for_each = { for e, p in each.value : trimprefix(e, "@") => p if startswith(e, "@") } + content { + team_id = team.key + permission = team.value + } + } + + depends_on = [github_team.this] +} + +resource "github_repository_file" "codeowners" { + for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 } + + repository = github_repository.this[each.key].name + branch = github_branch_default.this[each.key].branch + file = ".github/CODEOWNERS" + content = "* ${join(" ", [for e in each.value.maintainers : startswith(e, "@") ? "@${var.owner}/${trimprefix(e, "@")}" : "@${e}"])}\n" + commit_message = "add initial CODEOWNERS" + overwrite_on_create = false + + lifecycle { + ignore_changes = [content] + } +} + +resource "github_repository_ruleset" "this" { + for_each = local.repository_ruleset + + name = each.value.ruleset.name + repository = github_repository.this[each.value.repository].name + target = each.value.ruleset.target + enforcement = each.value.ruleset.enforcement + + dynamic "conditions" { + for_each = each.value.ruleset.conditions[*] + content { + ref_name { + include = conditions.value.ref_name.include + exclude = conditions.value.ref_name.exclude + } + } + } + + rules { + deletion = each.value.ruleset.rules.deletion + non_fast_forward = each.value.ruleset.rules.non_fast_forward + + dynamic "pull_request" { + for_each = each.value.ruleset.rules.pull_request[*] + content { + required_approving_review_count = pull_request.value.required_approving_review_count + dismiss_stale_reviews_on_push = pull_request.value.dismiss_stale_reviews_on_push + require_code_owner_review = pull_request.value.require_code_owner_review + require_last_push_approval = pull_request.value.require_last_push_approval + required_review_thread_resolution = pull_request.value.required_review_thread_resolution + } + } + + dynamic "required_status_checks" { + for_each = each.value.ruleset.rules.required_status_checks[*] + content { + strict_required_status_checks_policy = required_status_checks.value.strict + dynamic "required_check" { + for_each = toset(required_status_checks.value.contexts) + content { + context = required_check.value + } + } + } + } + } + + depends_on = [github_repository_file.codeowners] +} diff --git a/modules/github_org/terraform.tf b/modules/github_org/terraform.tf new file mode 100644 index 0000000..96e79de --- /dev/null +++ b/modules/github_org/terraform.tf @@ -0,0 +1,9 @@ +terraform { + required_version = ">= 1.10" + required_providers { + github = { + source = "integrations/github" + version = "6.13.0" + } + } +} diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl new file mode 100644 index 0000000..e756662 --- /dev/null +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -0,0 +1,48 @@ +mock_provider "github" {} + +variables { + owner = "IUCLabs" + team = { + maintainers = { name = "maintainers", maintainers = ["alice"], members = ["bob"] } + } + ruleset = { + default = { name = "default", rules = { deletion = true, pull_request = {} } } + } +} + +run "public_repo_with_ruleset" { + command = plan + + variables { + repository = { + ".github" = { name = ".github", private = false, rulesets = ["default"], maintainers = ["@maintainers", "carol"], codeowners = ["carol", "dave"] } + } + } + + assert { + condition = github_repository_file.codeowners[".github"].content == "* @IUCLabs/maintainers @carol\n" + error_message = "CODEOWNERS must list maintainers, teams qualified by owner" + } + + assert { + condition = local.repository_access[".github"] == { "@maintainers" = "maintain", carol = "maintain", dave = "push" } + error_message = "maintainers get maintain (winning over codeowners), codeowners get push" + } + + assert { + condition = length(github_repository_ruleset.this) == 1 && length(github_team_membership.this) == 2 + error_message = "expected one ruleset and two team memberships" + } +} + +run "private_repo_with_ruleset_rejected" { + command = plan + + variables { + repository = { + secret = { name = "secret", private = true, rulesets = ["default"] } + } + } + + expect_failures = [var.repository] +} diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf new file mode 100644 index 0000000..d061682 --- /dev/null +++ b/modules/github_org/variables.tf @@ -0,0 +1,74 @@ +variable "owner" { + description = "GitHub organisation that owns every resource" + type = string +} + +variable "team" { + description = "Map of teams to create, keyed by name" + type = map(object({ + name = string + description = optional(string, "") + privacy = optional(string, "closed") + maintainers = optional(list(string), []) + members = optional(list(string), []) + })) + default = {} +} + +variable "ruleset" { + description = "Map of reusable repository ruleset definitions, keyed by name" + type = map(object({ + name = string + target = optional(string, "branch") + enforcement = optional(string, "active") + conditions = optional(object({ + ref_name = object({ + include = list(string) + exclude = optional(list(string), []) + }) + })) + rules = object({ + deletion = optional(bool, false) + non_fast_forward = optional(bool, false) + pull_request = optional(object({ + required_approving_review_count = optional(number, 0) + dismiss_stale_reviews_on_push = optional(bool, false) + require_code_owner_review = optional(bool, false) + require_last_push_approval = optional(bool, false) + required_review_thread_resolution = optional(bool, false) + })) + required_status_checks = optional(object({ + contexts = list(string) + strict = optional(bool, false) + })) + }) + })) + default = {} +} + +variable "repository" { + description = "Map of repositories to create, keyed by name" + type = map(object({ + name = string + description = optional(string, "") + private = optional(bool, true) + rulesets = optional(list(string), []) + maintainers = optional(list(string), []) + codeowners = optional(list(string), []) + default_branch = optional(string, "main") + has_issues = optional(bool, true) + has_wiki = optional(bool, false) + has_projects = optional(bool, false) + allow_squash_merge = optional(bool, true) + allow_merge_commit = optional(bool, false) + allow_rebase_merge = optional(bool, false) + delete_branch_on_merge = optional(bool, true) + auto_init = optional(bool, true) + })) + default = {} + + validation { + condition = alltrue([for repo in var.repository : !(repo.private && length(repo.rulesets) > 0)]) + error_message = "Rulesets are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.rulesets) > 0])}." + } +} From 691eca53ea206b4f04142b91ed35073d94a260a1 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Mon, 9 Nov 2026 23:58:40 +1100 Subject: [PATCH 2/9] scope GitHub App secret to the github unit, use team slugs --- Makefile | 5 +--- README.md | 2 +- environments/github/iuclabs/terragrunt.hcl | 14 +++++++++-- modules/github_org/main.tf | 8 +++--- .../github_org/tests/github_org.tftest.hcl | 25 ++++++++++++++++--- 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index 813d2b4..1aa2908 100644 --- a/Makefile +++ b/Makefile @@ -14,10 +14,7 @@ define vault_env fi && \ export CONSUL_HTTP_TOKEN=$$(vault read -field=token consul_root/au/syd1/creds/terraform-git) && \ export GITEA_TOKEN=$$(vault kv get -field=token kv/service/gitea/gitadmin/tokens/terraform-git) && \ - export WOODPECKER_TOKEN=$$(vault kv get -field=token kv/service/woodpecker/tokens/gitadmin) && \ - export GITHUB_APP_ID=$$(vault kv get -field=app_id kv/service/github/iuclabs/terraform) && \ - export GITHUB_APP_INSTALLATION_ID=$$(vault kv get -field=installation_id kv/service/github/iuclabs/terraform) && \ - export GITHUB_APP_PEM_FILE="$$(vault kv get -field=pem kv/service/github/iuclabs/terraform)" + export WOODPECKER_TOKEN=$$(vault kv get -field=token kv/service/woodpecker/tokens/gitadmin) endef init: diff --git a/README.md b/README.md index b41fbd2..222d223 100644 --- a/README.md +++ b/README.md @@ -44,4 +44,4 @@ maintainers: ["@maintainers"] codeowners: [] ``` -`maintainers` (users or `@team`) get `maintain` and seed the initial `.github/CODEOWNERS`, which is then left to humans. `codeowners` get `push` so they can be added to CODEOWNERS later. Private repositories cannot use rulesets on the free plan; plan fails if they do. +`maintainers` (users or `@team`) get `maintain` and seed the initial `.github/CODEOWNERS` on `auto_init` repositories, which is then left to humans. `codeowners` get `push` so they can be added to CODEOWNERS later. Private repositories cannot use rulesets on the free plan; plan fails if they do. diff --git a/environments/github/iuclabs/terragrunt.hcl b/environments/github/iuclabs/terragrunt.hcl index dd8f031..38aed34 100644 --- a/environments/github/iuclabs/terragrunt.hcl +++ b/environments/github/iuclabs/terragrunt.hcl @@ -9,12 +9,22 @@ include "config" { } locals { - owner = "IUCLabs" - github = include.config.locals.github + owner = "IUCLabs" + github = include.config.locals.github + vault_path = "kv/service/github/iuclabs/terraform" } terraform { source = "../../../modules/github_org" + + extra_arguments "github_app" { + commands = ["plan", "apply", "destroy", "refresh", "import"] + env_vars = { + GITHUB_APP_ID = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=app_id", local.vault_path) + GITHUB_APP_INSTALLATION_ID = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=installation_id", local.vault_path) + GITHUB_APP_PEM_FILE = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=pem", local.vault_path) + } + } } generate "provider" { diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 9e52362..3229fb0 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -75,21 +75,19 @@ resource "github_repository_collaborators" "this" { dynamic "team" { for_each = { for e, p in each.value : trimprefix(e, "@") => p if startswith(e, "@") } content { - team_id = team.key + team_id = github_team.this[team.key].slug permission = team.value } } - - depends_on = [github_team.this] } resource "github_repository_file" "codeowners" { - for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 } + for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 && r.auto_init } repository = github_repository.this[each.key].name branch = github_branch_default.this[each.key].branch file = ".github/CODEOWNERS" - content = "* ${join(" ", [for e in each.value.maintainers : startswith(e, "@") ? "@${var.owner}/${trimprefix(e, "@")}" : "@${e}"])}\n" + content = "* ${join(" ", [for e in each.value.maintainers : startswith(e, "@") ? "@${var.owner}/${github_team.this[trimprefix(e, "@")].slug}" : "@${e}"])}\n" commit_message = "add initial CODEOWNERS" overwrite_on_create = false diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index e756662..62bdcde 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -1,4 +1,8 @@ -mock_provider "github" {} +mock_provider "github" { + mock_resource "github_team" { + defaults = { slug = "maintainers-slug" } + } +} variables { owner = "IUCLabs" @@ -20,8 +24,8 @@ run "public_repo_with_ruleset" { } assert { - condition = github_repository_file.codeowners[".github"].content == "* @IUCLabs/maintainers @carol\n" - error_message = "CODEOWNERS must list maintainers, teams qualified by owner" + condition = github_repository_file.codeowners[".github"].content == "* @IUCLabs/maintainers-slug @carol\n" + error_message = "CODEOWNERS must list maintainers, teams by owner-qualified slug" } assert { @@ -35,6 +39,21 @@ run "public_repo_with_ruleset" { } } +run "no_codeowners_without_auto_init" { + command = plan + + variables { + repository = { + empty = { name = "empty", private = false, auto_init = false, maintainers = ["@maintainers"] } + } + } + + assert { + condition = length(github_repository_file.codeowners) == 0 + error_message = "CODEOWNERS needs an initialised default branch" + } +} + run "private_repo_with_ruleset_rejected" { command = plan From 323cde9336be97cdba175c63ec349836eb543c32 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 00:05:34 +1100 Subject: [PATCH 3/9] fetch GitHub App creds in the Makefile, run gitea and github units separately --- Makefile | 48 +++++++++++++++------- environments/github/iuclabs/terragrunt.hcl | 14 +------ 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/Makefile b/Makefile index 1aa2908..829153e 100644 --- a/Makefile +++ b/Makefile @@ -5,8 +5,10 @@ VAULT_K8S_ROLE ?= woodpecker_terraform_git VAULT_K8S_MOUNT ?= auth/k8s/au/syd1 VAULT_K8S_JWT_PATH ?= /var/run/secrets/kubernetes.io/serviceaccount/token +GITHUB_VAULT_PATH ?= kv/service/github/iuclabs/terraform + define vault_env - @export VAULT_ADDR="https://vault.service.consul:8200" && \ + export VAULT_ADDR="https://vault.service.consul:8200" && \ if [ "$(VAULT_AUTH_METHOD)" = "kubernetes" ]; then \ export VAULT_TOKEN=$$(vault write -field=token $(VAULT_K8S_MOUNT)/login role=$(VAULT_K8S_ROLE) jwt=$$(cat $(VAULT_K8S_JWT_PATH))); \ else \ @@ -17,30 +19,46 @@ define vault_env export WOODPECKER_TOKEN=$$(vault kv get -field=token kv/service/woodpecker/tokens/gitadmin) endef -init: - @$(call vault_env) && \ - terragrunt run --all --non-interactive init -- -upgrade +define github_env + GITHUB_APP_ID=$$(vault kv get -field=app_id $(GITHUB_VAULT_PATH)) && \ + GITHUB_APP_INSTALLATION_ID=$$(vault kv get -field=installation_id $(GITHUB_VAULT_PATH)) && \ + GITHUB_APP_PEM_FILE=$$(vault kv get -field=pem $(GITHUB_VAULT_PATH)) && \ + export GITHUB_APP_ID GITHUB_APP_INSTALLATION_ID GITHUB_APP_PEM_FILE +endef -plan: init - @$(call vault_env) && \ - terragrunt run --all --parallelism 4 --non-interactive plan -- -lock=false +# Runs $(1) in $$dir for the gitea units, then the github units with App creds in a subshell; either failing fails the target without skipping the other. +define each_host + $(vault_env) || exit 1; \ + rc=0; \ + dir=environments/au; ( $(1) ) || rc=1; \ + dir=environments/github; ( $(github_env) || exit 1; $(1) ) || rc=1; \ + exit $$rc +endef -apply-if-changes: init - @$(call vault_env) && \ - terragrunt run --all --parallelism 4 --non-interactive plan -- -detailed-exitcode -out=tfplan; \ +define plan_then_apply + terragrunt run --all --working-dir $$dir --parallelism 4 --non-interactive plan -- -detailed-exitcode -out=tfplan; \ EXIT_CODE=$$?; \ if [ $$EXIT_CODE -eq 2 ]; then \ - $(call vault_env) && \ - terragrunt run --all --parallelism 2 --non-interactive apply -- tfplan; \ + terragrunt run --all --working-dir $$dir --parallelism 2 --non-interactive apply -- tfplan; \ elif [ $$EXIT_CODE -eq 0 ]; then \ - echo "No changes detected, skipping apply."; \ + echo "No changes detected in $$dir, skipping apply."; \ else \ exit $$EXIT_CODE; \ fi +endef + +init: + @$(vault_env) && \ + terragrunt run --all --non-interactive init -- -upgrade + +plan: init + @$(call each_host,terragrunt run --all --working-dir $$dir --parallelism 4 --non-interactive plan -- -lock=false) + +apply-if-changes: init + @$(call each_host,$(plan_then_apply)) apply: init - @$(call vault_env) && \ - terragrunt run --all --parallelism 2 --non-interactive apply + @$(call each_host,terragrunt run --all --working-dir $$dir --parallelism 2 --non-interactive apply) format: @echo "Formatting OpenTofu files..." diff --git a/environments/github/iuclabs/terragrunt.hcl b/environments/github/iuclabs/terragrunt.hcl index 38aed34..dd8f031 100644 --- a/environments/github/iuclabs/terragrunt.hcl +++ b/environments/github/iuclabs/terragrunt.hcl @@ -9,22 +9,12 @@ include "config" { } locals { - owner = "IUCLabs" - github = include.config.locals.github - vault_path = "kv/service/github/iuclabs/terraform" + owner = "IUCLabs" + github = include.config.locals.github } terraform { source = "../../../modules/github_org" - - extra_arguments "github_app" { - commands = ["plan", "apply", "destroy", "refresh", "import"] - env_vars = { - GITHUB_APP_ID = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=app_id", local.vault_path) - GITHUB_APP_INSTALLATION_ID = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=installation_id", local.vault_path) - GITHUB_APP_PEM_FILE = run_cmd("--terragrunt-quiet", "vault", "kv", "get", "-field=pem", local.vault_path) - } - } } generate "provider" { From a99c8f04fddd8d3229ff7e06081b5af47aee53dd Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 00:05:34 +1100 Subject: [PATCH 4/9] archive github repos on destroy, reject unknown rulesets --- modules/github_org/main.tf | 1 + modules/github_org/tests/github_org.tftest.hcl | 12 ++++++++++++ modules/github_org/variables.tf | 5 +++++ 3 files changed, 18 insertions(+) diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 3229fb0..293d971 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -50,6 +50,7 @@ resource "github_repository" "this" { allow_rebase_merge = each.value.allow_rebase_merge delete_branch_on_merge = each.value.delete_branch_on_merge auto_init = each.value.auto_init + archive_on_destroy = true } resource "github_branch_default" "this" { diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index 62bdcde..3c5e53b 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -65,3 +65,15 @@ run "private_repo_with_ruleset_rejected" { expect_failures = [var.repository] } + +run "unknown_ruleset_rejected" { + command = plan + + variables { + repository = { + public = { name = "public", private = false, rulesets = ["missing"] } + } + } + + expect_failures = [var.repository] +} diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf index d061682..e79ef15 100644 --- a/modules/github_org/variables.tf +++ b/modules/github_org/variables.tf @@ -71,4 +71,9 @@ variable "repository" { condition = alltrue([for repo in var.repository : !(repo.private && length(repo.rulesets) > 0)]) error_message = "Rulesets are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.rulesets) > 0])}." } + + validation { + condition = alltrue(flatten([for repo in var.repository : [for rs in repo.rulesets : contains(keys(var.ruleset), rs)]])) + error_message = "Unknown rulesets referenced: ${join(", ", distinct(flatten([for name, repo in var.repository : [for rs in repo.rulesets : "${name}/${rs}" if !contains(keys(var.ruleset), rs)]])))}." + } } From 132e93c0d4a185c5828822db357d89ffa7221108 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 21:52:52 +1100 Subject: [PATCH 5/9] generate github rulesets from repo flags, trim repo schema --- README.md | 36 ++--- .../IUCLabs/repository/.github.yaml | 3 - .../github.com/IUCLabs/ruleset/default.yaml | 12 -- modules/github_org/main.tf | 68 ++++++++-- .../github_org/tests/github_org.tftest.hcl | 124 ++++++++++++++++-- modules/github_org/variables.tf | 36 +++-- 6 files changed, 212 insertions(+), 67 deletions(-) delete mode 100644 config/github.com/IUCLabs/ruleset/default.yaml diff --git a/README.md b/README.md index 222d223..b0151dd 100644 --- a/README.md +++ b/README.md @@ -15,33 +15,33 @@ maintainers: [neoloc] members: [] ``` -`ruleset/.yaml` (applied per repository; org rulesets need a paid plan): +`repository/.yaml` (every field, with defaults): + +```yaml +description: "" +private: true +default_branch: main +maintainers: [] # users or @team: maintain access, seed initial .github/CODEOWNERS +codeowners: [] # push access, for adding to CODEOWNERS later +merge_type: squash # squash | merge | rebase +delete_branch_on_merge: true +branch_protection: !private # generated `branch-protection` ruleset on the default branch +required_checks: [] # generated `required-checks` ruleset (strict) +rulesets: [] # custom rulesets from ruleset/ +``` + +`ruleset/.yaml` (custom extras; `branch-protection` and `required-checks` are reserved): ```yaml target: branch enforcement: active conditions: ref_name: - include: ["~DEFAULT_BRANCH"] + include: ["refs/heads/release/*"] exclude: [] rules: deletion: true non_fast_forward: true - pull_request: - required_approving_review_count: 0 - dismiss_stale_reviews_on_push: true - required_status_checks: - contexts: [ci/woodpecker] ``` -`repository/.yaml` (squash-only, delete branch on merge, `main` by default): - -```yaml -description: "IUCLabs organisation profile" -private: false -rulesets: [default] -maintainers: ["@maintainers"] -codeowners: [] -``` - -`maintainers` (users or `@team`) get `maintain` and seed the initial `.github/CODEOWNERS` on `auto_init` repositories, which is then left to humans. `codeowners` get `push` so they can be added to CODEOWNERS later. Private repositories cannot use rulesets on the free plan; plan fails if they do. +Private repositories cannot use `branch_protection`, `required_checks` or `rulesets` on the free plan; plan fails if they do. diff --git a/config/github.com/IUCLabs/repository/.github.yaml b/config/github.com/IUCLabs/repository/.github.yaml index b08224c..9a8a208 100644 --- a/config/github.com/IUCLabs/repository/.github.yaml +++ b/config/github.com/IUCLabs/repository/.github.yaml @@ -1,7 +1,4 @@ description: "IUCLabs organisation profile" private: false -rulesets: - - default maintainers: - "@maintainers" -codeowners: [] diff --git a/config/github.com/IUCLabs/ruleset/default.yaml b/config/github.com/IUCLabs/ruleset/default.yaml deleted file mode 100644 index 1715997..0000000 --- a/config/github.com/IUCLabs/ruleset/default.yaml +++ /dev/null @@ -1,12 +0,0 @@ -target: branch -enforcement: active -conditions: - ref_name: - include: ["~DEFAULT_BRANCH"] - exclude: [] -rules: - deletion: true - non_fast_forward: true - pull_request: - required_approving_review_count: 0 - dismiss_stale_reviews_on_push: true diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 293d971..09ce5fc 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -13,11 +13,53 @@ locals { ) } - repository_ruleset = merge([ - for name, r in var.repository : { - for rs in r.rulesets : "${name}/${rs}" => { repository = name, ruleset = var.ruleset[rs] } - } - ]...) + default_branch_rules = { + target = "branch" + enforcement = "active" + conditions = { ref_name = { include = ["~DEFAULT_BRANCH"], exclude = [] } } + } + + repository_ruleset = merge(concat( + [ + for name, r in var.repository : { + for rs in r.rulesets : "${name}/${rs}" => { repository = name, ruleset = var.ruleset[rs] } + } + ], + [{ + for name, r in var.repository : "${name}/branch-protection" => { + repository = name + ruleset = merge(local.default_branch_rules, { + name = "branch-protection" + rules = { + deletion = true + non_fast_forward = true + pull_request = { + required_approving_review_count = 0 + dismiss_stale_reviews_on_push = true + require_code_owner_review = false + require_last_push_approval = false + required_review_thread_resolution = false + } + required_status_checks = null + } + }) + } if coalesce(r.branch_protection, !r.private) + }, + { + for name, r in var.repository : "${name}/required-checks" => { + repository = name + ruleset = merge(local.default_branch_rules, { + name = "required-checks" + rules = { + deletion = false + non_fast_forward = false + pull_request = null + required_status_checks = { contexts = r.required_checks, strict = true } + } + }) + } if length(r.required_checks) > 0 + }], + )...) } resource "github_team" "this" { @@ -42,14 +84,14 @@ resource "github_repository" "this" { name = each.value.name description = each.value.description visibility = each.value.private ? "private" : "public" - has_issues = each.value.has_issues - has_wiki = each.value.has_wiki - has_projects = each.value.has_projects - allow_squash_merge = each.value.allow_squash_merge - allow_merge_commit = each.value.allow_merge_commit - allow_rebase_merge = each.value.allow_rebase_merge + has_issues = true + has_wiki = false + has_projects = false + allow_squash_merge = each.value.merge_type == "squash" + allow_merge_commit = each.value.merge_type == "merge" + allow_rebase_merge = each.value.merge_type == "rebase" delete_branch_on_merge = each.value.delete_branch_on_merge - auto_init = each.value.auto_init + auto_init = true archive_on_destroy = true } @@ -83,7 +125,7 @@ resource "github_repository_collaborators" "this" { } resource "github_repository_file" "codeowners" { - for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 && r.auto_init } + for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 } repository = github_repository.this[each.key].name branch = github_branch_default.this[each.key].branch diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index 3c5e53b..f839c1c 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -10,16 +10,16 @@ variables { maintainers = { name = "maintainers", maintainers = ["alice"], members = ["bob"] } } ruleset = { - default = { name = "default", rules = { deletion = true, pull_request = {} } } + signed = { name = "signed", rules = { deletion = true, pull_request = {} } } } } -run "public_repo_with_ruleset" { +run "public_repo_defaults" { command = plan variables { repository = { - ".github" = { name = ".github", private = false, rulesets = ["default"], maintainers = ["@maintainers", "carol"], codeowners = ["carol", "dave"] } + ".github" = { name = ".github", private = false, maintainers = ["@maintainers", "carol"], codeowners = ["carol", "dave"] } } } @@ -34,38 +34,140 @@ run "public_repo_with_ruleset" { } assert { - condition = length(github_repository_ruleset.this) == 1 && length(github_team_membership.this) == 2 - error_message = "expected one ruleset and two team memberships" + condition = keys(github_repository_ruleset.this) == [".github/branch-protection"] && length(github_team_membership.this) == 2 + error_message = "public repo must get only the generated branch-protection ruleset" + } + + assert { + condition = ( + github_repository.this[".github"].allow_squash_merge && + !github_repository.this[".github"].allow_merge_commit && + !github_repository.this[".github"].allow_rebase_merge + ) + error_message = "merge_type defaults to squash only" } } -run "no_codeowners_without_auto_init" { +run "private_repo_defaults" { command = plan variables { repository = { - empty = { name = "empty", private = false, auto_init = false, maintainers = ["@maintainers"] } + secret = { name = "secret", maintainers = ["@maintainers"] } } } assert { - condition = length(github_repository_file.codeowners) == 0 - error_message = "CODEOWNERS needs an initialised default branch" + condition = length(github_repository_ruleset.this) == 0 && length(github_repository_file.codeowners) == 1 + error_message = "private repo defaults to no rulesets but still gets CODEOWNERS" } } -run "private_repo_with_ruleset_rejected" { +run "merge_type_rebase" { command = plan variables { repository = { - secret = { name = "secret", private = true, rulesets = ["default"] } + r = { name = "r", merge_type = "rebase" } + m = { name = "m", merge_type = "merge" } + } + } + + assert { + condition = ( + github_repository.this["r"].allow_rebase_merge && !github_repository.this["r"].allow_squash_merge && !github_repository.this["r"].allow_merge_commit && + github_repository.this["m"].allow_merge_commit && !github_repository.this["m"].allow_squash_merge && !github_repository.this["m"].allow_rebase_merge + ) + error_message = "merge_type must enable exactly the matching allow_* flag" + } +} + +run "invalid_merge_type_rejected" { + command = plan + + variables { + repository = { + bad = { name = "bad", merge_type = "fast-forward" } } } expect_failures = [var.repository] } +run "generated_and_custom_rulesets" { + command = plan + + variables { + repository = { + checked = { name = "checked", private = false, branch_protection = false, required_checks = ["ci/woodpecker"], rulesets = ["signed"] } + } + } + + assert { + condition = toset(keys(github_repository_ruleset.this)) == toset(["checked/required-checks", "checked/signed"]) + error_message = "required_checks without branch_protection yields only required-checks plus custom rulesets" + } + + assert { + condition = github_repository_ruleset.this["checked/required-checks"].rules[0].required_status_checks[0].strict_required_status_checks_policy + error_message = "required-checks ruleset must be strict" + } + + assert { + condition = length(github_repository_ruleset.this["checked/required-checks"].rules[0].pull_request) == 0 + error_message = "required-checks ruleset must not carry pull_request rules" + } +} + +run "private_branch_protection_rejected" { + command = plan + + variables { + repository = { + secret = { name = "secret", branch_protection = true } + } + } + + expect_failures = [var.repository] +} + +run "private_required_checks_rejected" { + command = plan + + variables { + repository = { + secret = { name = "secret", required_checks = ["ci/woodpecker"] } + } + } + + expect_failures = [var.repository] +} + +run "private_rulesets_rejected" { + command = plan + + variables { + repository = { + secret = { name = "secret", rulesets = ["signed"] } + } + } + + expect_failures = [var.repository] +} + +run "reserved_ruleset_name_rejected" { + command = plan + + variables { + ruleset = { + branch-protection = { name = "branch-protection", rules = { deletion = true } } + } + repository = {} + } + + expect_failures = [var.ruleset] +} + run "unknown_ruleset_rejected" { command = plan diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf index e79ef15..14ce930 100644 --- a/modules/github_org/variables.tf +++ b/modules/github_org/variables.tf @@ -44,6 +44,11 @@ variable "ruleset" { }) })) default = {} + + validation { + condition = length(setintersection(keys(var.ruleset), ["branch-protection", "required-checks"])) == 0 + error_message = "Ruleset names branch-protection and required-checks are reserved for generated rulesets." + } } variable "repository" { @@ -52,24 +57,35 @@ variable "repository" { name = string description = optional(string, "") private = optional(bool, true) - rulesets = optional(list(string), []) + default_branch = optional(string, "main") maintainers = optional(list(string), []) codeowners = optional(list(string), []) - default_branch = optional(string, "main") - has_issues = optional(bool, true) - has_wiki = optional(bool, false) - has_projects = optional(bool, false) - allow_squash_merge = optional(bool, true) - allow_merge_commit = optional(bool, false) - allow_rebase_merge = optional(bool, false) + merge_type = optional(string, "squash") delete_branch_on_merge = optional(bool, true) - auto_init = optional(bool, true) + branch_protection = optional(bool) + required_checks = optional(list(string), []) + rulesets = optional(list(string), []) })) default = {} + validation { + condition = alltrue([for repo in var.repository : contains(["squash", "merge", "rebase"], repo.merge_type)]) + error_message = "merge_type must be squash, merge or rebase: ${join(", ", [for name, repo in var.repository : name if !contains(["squash", "merge", "rebase"], repo.merge_type)])}." + } + + validation { + condition = alltrue([for repo in var.repository : !(repo.private && coalesce(repo.branch_protection, false))]) + error_message = "branch_protection is not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && coalesce(repo.branch_protection, false)])}." + } + + validation { + condition = alltrue([for repo in var.repository : !(repo.private && length(repo.required_checks) > 0)]) + error_message = "required_checks are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.required_checks) > 0])}." + } + validation { condition = alltrue([for repo in var.repository : !(repo.private && length(repo.rulesets) > 0)]) - error_message = "Rulesets are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.rulesets) > 0])}." + error_message = "rulesets are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.rulesets) > 0])}." } validation { From d7359d1fc7840e543021d0d8eb8d70bbc51578ae Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 21:56:48 +1100 Subject: [PATCH 6/9] generate tag-protection ruleset for release tags --- README.md | 5 +- modules/github_org/main.tf | 17 ++++++ .../github_org/tests/github_org.tftest.hcl | 59 +++++++++++++++++-- modules/github_org/variables.tf | 10 +++- 4 files changed, 83 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index b0151dd..f4652f7 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,12 @@ codeowners: [] # push access, for adding to CODEOWNERS later merge_type: squash # squash | merge | rebase delete_branch_on_merge: true branch_protection: !private # generated `branch-protection` ruleset on the default branch +tag_protection: !private # generated `tag-protection` ruleset: refs/tags/v* undeletable, immutable required_checks: [] # generated `required-checks` ruleset (strict) rulesets: [] # custom rulesets from ruleset/ ``` -`ruleset/.yaml` (custom extras; `branch-protection` and `required-checks` are reserved): +`ruleset/.yaml` (custom extras; `branch-protection`, `required-checks` and `tag-protection` are reserved): ```yaml target: branch @@ -44,4 +45,4 @@ rules: non_fast_forward: true ``` -Private repositories cannot use `branch_protection`, `required_checks` or `rulesets` on the free plan; plan fails if they do. +Private repositories cannot use `branch_protection`, `tag_protection`, `required_checks` or `rulesets` on the free plan; plan fails if they do. diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 09ce5fc..51fefd9 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -58,6 +58,23 @@ locals { } }) } if length(r.required_checks) > 0 + }, + { + for name, r in var.repository : "${name}/tag-protection" => { + repository = name + ruleset = { + name = "tag-protection" + target = "tag" + enforcement = "active" + conditions = { ref_name = { include = ["refs/tags/v*"], exclude = [] } } + rules = { + deletion = true + non_fast_forward = true + pull_request = null + required_status_checks = null + } + } + } if coalesce(r.tag_protection, !r.private) }], )...) } diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index f839c1c..993406e 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -34,8 +34,19 @@ run "public_repo_defaults" { } assert { - condition = keys(github_repository_ruleset.this) == [".github/branch-protection"] && length(github_team_membership.this) == 2 - error_message = "public repo must get only the generated branch-protection ruleset" + condition = keys(github_repository_ruleset.this) == [".github/branch-protection", ".github/tag-protection"] && length(github_team_membership.this) == 2 + error_message = "public repo must get only the generated branch-protection and tag-protection rulesets" + } + + assert { + condition = ( + github_repository_ruleset.this[".github/tag-protection"].target == "tag" && + github_repository_ruleset.this[".github/tag-protection"].enforcement == "active" && + github_repository_ruleset.this[".github/tag-protection"].conditions[0].ref_name[0].include == tolist(["refs/tags/v*"]) && + github_repository_ruleset.this[".github/tag-protection"].rules[0].deletion && + github_repository_ruleset.this[".github/tag-protection"].rules[0].non_fast_forward + ) + error_message = "tag-protection ruleset must make refs/tags/v* undeletable and immutable" } assert { @@ -99,13 +110,13 @@ run "generated_and_custom_rulesets" { variables { repository = { - checked = { name = "checked", private = false, branch_protection = false, required_checks = ["ci/woodpecker"], rulesets = ["signed"] } + checked = { name = "checked", private = false, branch_protection = false, tag_protection = false, required_checks = ["ci/woodpecker"], rulesets = ["signed"] } } } assert { condition = toset(keys(github_repository_ruleset.this)) == toset(["checked/required-checks", "checked/signed"]) - error_message = "required_checks without branch_protection yields only required-checks plus custom rulesets" + error_message = "required_checks with protections off yields only required-checks plus custom rulesets" } assert { @@ -131,6 +142,46 @@ run "private_branch_protection_rejected" { expect_failures = [var.repository] } +run "public_tag_protection_only" { + command = plan + + variables { + repository = { + tags = { name = "tags", private = false, branch_protection = false } + } + } + + assert { + condition = keys(github_repository_ruleset.this) == ["tags/tag-protection"] + error_message = "tag_protection defaults on for public repos independently of branch_protection" + } +} + +run "private_tag_protection_rejected" { + command = plan + + variables { + repository = { + secret = { name = "secret", tag_protection = true } + } + } + + expect_failures = [var.repository] +} + +run "reserved_tag_protection_name_rejected" { + command = plan + + variables { + ruleset = { + tag-protection = { name = "tag-protection", target = "tag", rules = { deletion = true } } + } + repository = {} + } + + expect_failures = [var.ruleset] +} + run "private_required_checks_rejected" { command = plan diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf index 14ce930..f9b80f7 100644 --- a/modules/github_org/variables.tf +++ b/modules/github_org/variables.tf @@ -46,8 +46,8 @@ variable "ruleset" { default = {} validation { - condition = length(setintersection(keys(var.ruleset), ["branch-protection", "required-checks"])) == 0 - error_message = "Ruleset names branch-protection and required-checks are reserved for generated rulesets." + condition = length(setintersection(keys(var.ruleset), ["branch-protection", "required-checks", "tag-protection"])) == 0 + error_message = "Ruleset names branch-protection, required-checks and tag-protection are reserved for generated rulesets." } } @@ -63,6 +63,7 @@ variable "repository" { merge_type = optional(string, "squash") delete_branch_on_merge = optional(bool, true) branch_protection = optional(bool) + tag_protection = optional(bool) required_checks = optional(list(string), []) rulesets = optional(list(string), []) })) @@ -78,6 +79,11 @@ variable "repository" { error_message = "branch_protection is not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && coalesce(repo.branch_protection, false)])}." } + validation { + condition = alltrue([for repo in var.repository : !(repo.private && coalesce(repo.tag_protection, false))]) + error_message = "tag_protection is not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && coalesce(repo.tag_protection, false)])}." + } + validation { condition = alltrue([for repo in var.repository : !(repo.private && length(repo.required_checks) > 0)]) error_message = "required_checks are not enforced on private repositories on the GitHub free plan: ${join(", ", [for name, repo in var.repository : name if repo.private && length(repo.required_checks) > 0])}." From 23c315a49aac2e5714911ae95a087a678ebf42bb Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 22:01:33 +1100 Subject: [PATCH 7/9] rename auto-init main to default_branch and reject invalid ruleset shapes --- modules/github_org/main.tf | 3 + .../github_org/tests/github_org.tftest.hcl | 63 +++++++++++++++++++ modules/github_org/variables.tf | 10 +++ 3 files changed, 76 insertions(+) diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 51fefd9..686a773 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -117,6 +117,9 @@ resource "github_branch_default" "this" { repository = github_repository.this[each.key].name branch = each.value.default_branch + # auto_init only creates main; rename it instead of pointing at a missing branch + rename = true + wait_for_rename = true } resource "github_repository_collaborators" "this" { diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index 993406e..0d7d4fc 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -230,3 +230,66 @@ run "unknown_ruleset_rejected" { expect_failures = [var.repository] } + +run "non_main_default_branch_renamed" { + command = plan + + variables { + repository = { + legacy = { name = "legacy", default_branch = "master", maintainers = ["carol"] } + } + } + + assert { + condition = ( + github_branch_default.this["legacy"].branch == "master" && + github_branch_default.this["legacy"].rename && + github_branch_default.this["legacy"].wait_for_rename + ) + error_message = "default_branch must rename the auto-init main and wait for it to propagate" + } + + assert { + condition = github_repository_file.codeowners["legacy"].branch == "master" + error_message = "CODEOWNERS must be committed to the renamed default branch" + } +} + +run "tag_ruleset_pull_request_rejected" { + command = plan + + variables { + ruleset = { + tagpr = { name = "tagpr", target = "tag", rules = { pull_request = {} } } + } + repository = {} + } + + expect_failures = [var.ruleset] +} + +run "tag_ruleset_status_checks_rejected" { + command = plan + + variables { + ruleset = { + tagci = { name = "tagci", target = "tag", rules = { required_status_checks = { contexts = ["ci"] } } } + } + repository = {} + } + + expect_failures = [var.ruleset] +} + +run "empty_status_check_contexts_rejected" { + command = plan + + variables { + ruleset = { + noci = { name = "noci", rules = { required_status_checks = { contexts = [] } } } + } + repository = {} + } + + expect_failures = [var.ruleset] +} diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf index f9b80f7..4781959 100644 --- a/modules/github_org/variables.tf +++ b/modules/github_org/variables.tf @@ -49,6 +49,16 @@ variable "ruleset" { condition = length(setintersection(keys(var.ruleset), ["branch-protection", "required-checks", "tag-protection"])) == 0 error_message = "Ruleset names branch-protection, required-checks and tag-protection are reserved for generated rulesets." } + + validation { + condition = alltrue([for rs in var.ruleset : rs.target == "branch" || (rs.rules.pull_request == null && rs.rules.required_status_checks == null)]) + error_message = "pull_request and required_status_checks are branch-only rules, not allowed on tag rulesets: ${join(", ", [for k, rs in var.ruleset : k if rs.target != "branch" && (rs.rules.pull_request != null || rs.rules.required_status_checks != null)])}." + } + + validation { + condition = alltrue([for rs in var.ruleset : rs.rules.required_status_checks == null || length(rs.rules.required_status_checks.contexts) > 0]) + error_message = "required_status_checks.contexts must not be empty: ${join(", ", [for k, rs in var.ruleset : k if rs.rules.required_status_checks != null && length(rs.rules.required_status_checks.contexts) == 0])}." + } } variable "repository" { From d6d608b2a15aeee396fcb818f8f2c88f0e626db9 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 22:32:17 +1100 Subject: [PATCH 8/9] split github_org into team, repository and ruleset submodules --- README.md | 2 + modules/github_org/main.tf | 208 +----------------- modules/github_org/modules/repository/main.tf | 131 +++++++++++ .../github_org/modules/repository/outputs.tf | 19 ++ .../modules/repository/terraform.tf | 9 + .../modules/repository/variables.tf | 31 +++ modules/github_org/modules/ruleset/main.tf | 45 ++++ modules/github_org/modules/ruleset/outputs.tf | 3 + .../github_org/modules/ruleset/terraform.tf | 9 + .../github_org/modules/ruleset/variables.tf | 32 +++ modules/github_org/modules/team/main.tf | 16 ++ modules/github_org/modules/team/outputs.tf | 11 + modules/github_org/modules/team/terraform.tf | 9 + modules/github_org/modules/team/variables.tf | 23 ++ .../github_org/tests/github_org.tftest.hcl | 44 ++-- 15 files changed, 373 insertions(+), 219 deletions(-) create mode 100644 modules/github_org/modules/repository/main.tf create mode 100644 modules/github_org/modules/repository/outputs.tf create mode 100644 modules/github_org/modules/repository/terraform.tf create mode 100644 modules/github_org/modules/repository/variables.tf create mode 100644 modules/github_org/modules/ruleset/main.tf create mode 100644 modules/github_org/modules/ruleset/outputs.tf create mode 100644 modules/github_org/modules/ruleset/terraform.tf create mode 100644 modules/github_org/modules/ruleset/variables.tf create mode 100644 modules/github_org/modules/team/main.tf create mode 100644 modules/github_org/modules/team/outputs.tf create mode 100644 modules/github_org/modules/team/terraform.tf create mode 100644 modules/github_org/modules/team/variables.tf diff --git a/README.md b/README.md index f4652f7..a403ca4 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Manage Gitea resources, teams, repos, and Woodpecker CI via Terraform. `config/github.com/IUCLabs/` feeds `modules/github_org` via `environments/github/iuclabs`, authenticated as a GitHub App (`kv/service/github/iuclabs/terraform`). Org membership invites are manual. +`modules/github_org` validates config and calls `modules/team` (team + memberships) and `modules/repository` (repo, default branch, collaborators, CODEOWNERS, rulesets via `modules/ruleset`). + `team/.yaml`: ```yaml diff --git a/modules/github_org/main.tf b/modules/github_org/main.tf index 686a773..4024d04 100644 --- a/modules/github_org/main.tf +++ b/modules/github_org/main.tf @@ -1,210 +1,24 @@ -locals { - team_membership = merge([ - for team, t in var.team : merge( - { for u in t.members : "${team}/${u}" => { team = team, username = u, role = "member" } }, - { for u in t.maintainers : "${team}/${u}" => { team = team, username = u, role = "maintainer" } }, - ) - ]...) +module "team" { + source = "./modules/team" - repository_access = { - for name, r in var.repository : name => merge( - { for e in r.codeowners : e => "push" }, - { for e in r.maintainers : e => "maintain" }, - ) - } - - default_branch_rules = { - target = "branch" - enforcement = "active" - conditions = { ref_name = { include = ["~DEFAULT_BRANCH"], exclude = [] } } - } - - repository_ruleset = merge(concat( - [ - for name, r in var.repository : { - for rs in r.rulesets : "${name}/${rs}" => { repository = name, ruleset = var.ruleset[rs] } - } - ], - [{ - for name, r in var.repository : "${name}/branch-protection" => { - repository = name - ruleset = merge(local.default_branch_rules, { - name = "branch-protection" - rules = { - deletion = true - non_fast_forward = true - pull_request = { - required_approving_review_count = 0 - dismiss_stale_reviews_on_push = true - require_code_owner_review = false - require_last_push_approval = false - required_review_thread_resolution = false - } - required_status_checks = null - } - }) - } if coalesce(r.branch_protection, !r.private) - }, - { - for name, r in var.repository : "${name}/required-checks" => { - repository = name - ruleset = merge(local.default_branch_rules, { - name = "required-checks" - rules = { - deletion = false - non_fast_forward = false - pull_request = null - required_status_checks = { contexts = r.required_checks, strict = true } - } - }) - } if length(r.required_checks) > 0 - }, - { - for name, r in var.repository : "${name}/tag-protection" => { - repository = name - ruleset = { - name = "tag-protection" - target = "tag" - enforcement = "active" - conditions = { ref_name = { include = ["refs/tags/v*"], exclude = [] } } - rules = { - deletion = true - non_fast_forward = true - pull_request = null - required_status_checks = null - } - } - } if coalesce(r.tag_protection, !r.private) - }], - )...) -} - -resource "github_team" "this" { for_each = var.team name = each.value.name description = each.value.description privacy = each.value.privacy + maintainers = each.value.maintainers + members = each.value.members } -resource "github_team_membership" "this" { - for_each = local.team_membership +module "repository" { + source = "./modules/repository" - team_id = github_team.this[each.value.team].id - username = each.value.username - role = each.value.role -} - -resource "github_repository" "this" { for_each = var.repository - name = each.value.name - description = each.value.description - visibility = each.value.private ? "private" : "public" - has_issues = true - has_wiki = false - has_projects = false - allow_squash_merge = each.value.merge_type == "squash" - allow_merge_commit = each.value.merge_type == "merge" - allow_rebase_merge = each.value.merge_type == "rebase" - delete_branch_on_merge = each.value.delete_branch_on_merge - auto_init = true - archive_on_destroy = true -} - -resource "github_branch_default" "this" { - for_each = var.repository - - repository = github_repository.this[each.key].name - branch = each.value.default_branch - # auto_init only creates main; rename it instead of pointing at a missing branch - rename = true - wait_for_rename = true -} - -resource "github_repository_collaborators" "this" { - for_each = { for name, access in local.repository_access : name => access if length(access) > 0 } - - repository = github_repository.this[each.key].name - - dynamic "user" { - for_each = { for e, p in each.value : e => p if !startswith(e, "@") } - content { - username = user.key - permission = user.value - } - } - - dynamic "team" { - for_each = { for e, p in each.value : trimprefix(e, "@") => p if startswith(e, "@") } - content { - team_id = github_team.this[team.key].slug - permission = team.value - } + owner = var.owner + config = each.value + rulesets = { for rs in each.value.rulesets : rs => var.ruleset[rs] } + team_slugs = { + for e in concat(each.value.maintainers, each.value.codeowners) : trimprefix(e, "@") => module.team[trimprefix(e, "@")].slug if startswith(e, "@") } } - -resource "github_repository_file" "codeowners" { - for_each = { for name, r in var.repository : name => r if length(r.maintainers) > 0 } - - repository = github_repository.this[each.key].name - branch = github_branch_default.this[each.key].branch - file = ".github/CODEOWNERS" - content = "* ${join(" ", [for e in each.value.maintainers : startswith(e, "@") ? "@${var.owner}/${github_team.this[trimprefix(e, "@")].slug}" : "@${e}"])}\n" - commit_message = "add initial CODEOWNERS" - overwrite_on_create = false - - lifecycle { - ignore_changes = [content] - } -} - -resource "github_repository_ruleset" "this" { - for_each = local.repository_ruleset - - name = each.value.ruleset.name - repository = github_repository.this[each.value.repository].name - target = each.value.ruleset.target - enforcement = each.value.ruleset.enforcement - - dynamic "conditions" { - for_each = each.value.ruleset.conditions[*] - content { - ref_name { - include = conditions.value.ref_name.include - exclude = conditions.value.ref_name.exclude - } - } - } - - rules { - deletion = each.value.ruleset.rules.deletion - non_fast_forward = each.value.ruleset.rules.non_fast_forward - - dynamic "pull_request" { - for_each = each.value.ruleset.rules.pull_request[*] - content { - required_approving_review_count = pull_request.value.required_approving_review_count - dismiss_stale_reviews_on_push = pull_request.value.dismiss_stale_reviews_on_push - require_code_owner_review = pull_request.value.require_code_owner_review - require_last_push_approval = pull_request.value.require_last_push_approval - required_review_thread_resolution = pull_request.value.required_review_thread_resolution - } - } - - dynamic "required_status_checks" { - for_each = each.value.ruleset.rules.required_status_checks[*] - content { - strict_required_status_checks_policy = required_status_checks.value.strict - dynamic "required_check" { - for_each = toset(required_status_checks.value.contexts) - content { - context = required_check.value - } - } - } - } - } - - depends_on = [github_repository_file.codeowners] -} diff --git a/modules/github_org/modules/repository/main.tf b/modules/github_org/modules/repository/main.tf new file mode 100644 index 0000000..f092097 --- /dev/null +++ b/modules/github_org/modules/repository/main.tf @@ -0,0 +1,131 @@ +locals { + access = merge( + { for e in var.config.codeowners : e => "push" }, + { for e in var.config.maintainers : e => "maintain" }, + ) + + default_branch_rules = { + target = "branch" + enforcement = "active" + conditions = { ref_name = { include = ["~DEFAULT_BRANCH"], exclude = [] } } + } + + generated_rulesets = { for k, v in { + branch-protection = { + enabled = coalesce(var.config.branch_protection, !var.config.private) + ruleset = merge(local.default_branch_rules, { + name = "branch-protection" + rules = { + deletion = true + non_fast_forward = true + pull_request = { + required_approving_review_count = 0 + dismiss_stale_reviews_on_push = true + require_code_owner_review = false + require_last_push_approval = false + required_review_thread_resolution = false + } + required_status_checks = null + } + }) + } + required-checks = { + enabled = length(var.config.required_checks) > 0 + ruleset = merge(local.default_branch_rules, { + name = "required-checks" + rules = { + deletion = false + non_fast_forward = false + pull_request = null + required_status_checks = { contexts = var.config.required_checks, strict = true } + } + }) + } + tag-protection = { + enabled = coalesce(var.config.tag_protection, !var.config.private) + ruleset = { + name = "tag-protection" + target = "tag" + enforcement = "active" + conditions = { ref_name = { include = ["refs/tags/v*"], exclude = [] } } + rules = { + deletion = true + non_fast_forward = true + pull_request = null + required_status_checks = null + } + } + } + } : k => v.ruleset if v.enabled } +} + +resource "github_repository" "this" { + name = var.config.name + description = var.config.description + visibility = var.config.private ? "private" : "public" + has_issues = true + has_wiki = false + has_projects = false + allow_squash_merge = var.config.merge_type == "squash" + allow_merge_commit = var.config.merge_type == "merge" + allow_rebase_merge = var.config.merge_type == "rebase" + delete_branch_on_merge = var.config.delete_branch_on_merge + auto_init = true + archive_on_destroy = true +} + +resource "github_branch_default" "this" { + repository = github_repository.this.name + branch = var.config.default_branch + # auto_init only creates main; rename it instead of pointing at a missing branch + rename = true + wait_for_rename = true +} + +resource "github_repository_collaborators" "this" { + count = length(local.access) > 0 ? 1 : 0 + + repository = github_repository.this.name + + dynamic "user" { + for_each = { for e, p in local.access : e => p if !startswith(e, "@") } + content { + username = user.key + permission = user.value + } + } + + dynamic "team" { + for_each = { for e, p in local.access : trimprefix(e, "@") => p if startswith(e, "@") } + content { + team_id = var.team_slugs[team.key] + permission = team.value + } + } +} + +resource "github_repository_file" "codeowners" { + count = length(var.config.maintainers) > 0 ? 1 : 0 + + repository = github_repository.this.name + branch = github_branch_default.this.branch + file = ".github/CODEOWNERS" + content = "* ${join(" ", [for e in var.config.maintainers : startswith(e, "@") ? "@${var.owner}/${var.team_slugs[trimprefix(e, "@")]}" : "@${e}"])}\n" + commit_message = "add initial CODEOWNERS" + overwrite_on_create = false + + lifecycle { + ignore_changes = [content] + } +} + +module "ruleset" { + source = "../ruleset" + + for_each = merge(var.rulesets, local.generated_rulesets) + + repository = github_repository.this.name + ruleset = each.value + + depends_on = [github_repository_file.codeowners] +} diff --git a/modules/github_org/modules/repository/outputs.tf b/modules/github_org/modules/repository/outputs.tf new file mode 100644 index 0000000..1ac9d23 --- /dev/null +++ b/modules/github_org/modules/repository/outputs.tf @@ -0,0 +1,19 @@ +output "repository" { + value = github_repository.this +} + +output "branch_default" { + value = github_branch_default.this +} + +output "codeowners" { + value = one(github_repository_file.codeowners) +} + +output "access" { + value = local.access +} + +output "rulesets" { + value = { for k, m in module.ruleset : k => m.ruleset } +} diff --git a/modules/github_org/modules/repository/terraform.tf b/modules/github_org/modules/repository/terraform.tf new file mode 100644 index 0000000..96e79de --- /dev/null +++ b/modules/github_org/modules/repository/terraform.tf @@ -0,0 +1,9 @@ +terraform { + required_version = ">= 1.10" + required_providers { + github = { + source = "integrations/github" + version = "6.13.0" + } + } +} diff --git a/modules/github_org/modules/repository/variables.tf b/modules/github_org/modules/repository/variables.tf new file mode 100644 index 0000000..89f0771 --- /dev/null +++ b/modules/github_org/modules/repository/variables.tf @@ -0,0 +1,31 @@ +variable "owner" { + type = string +} + +variable "config" { + type = object({ + name = string + description = string + private = bool + default_branch = string + maintainers = list(string) + codeowners = list(string) + merge_type = string + delete_branch_on_merge = bool + branch_protection = bool + tag_protection = bool + required_checks = list(string) + }) +} + +variable "rulesets" { + description = "Custom ruleset definitions this repository references, keyed by name" + type = any + default = {} +} + +variable "team_slugs" { + description = "Slugs of the teams this repository references, keyed by team name" + type = map(string) + default = {} +} diff --git a/modules/github_org/modules/ruleset/main.tf b/modules/github_org/modules/ruleset/main.tf new file mode 100644 index 0000000..44448cb --- /dev/null +++ b/modules/github_org/modules/ruleset/main.tf @@ -0,0 +1,45 @@ +resource "github_repository_ruleset" "this" { + name = var.ruleset.name + repository = var.repository + target = var.ruleset.target + enforcement = var.ruleset.enforcement + + dynamic "conditions" { + for_each = var.ruleset.conditions[*] + content { + ref_name { + include = conditions.value.ref_name.include + exclude = conditions.value.ref_name.exclude + } + } + } + + rules { + deletion = var.ruleset.rules.deletion + non_fast_forward = var.ruleset.rules.non_fast_forward + + dynamic "pull_request" { + for_each = var.ruleset.rules.pull_request[*] + content { + required_approving_review_count = pull_request.value.required_approving_review_count + dismiss_stale_reviews_on_push = pull_request.value.dismiss_stale_reviews_on_push + require_code_owner_review = pull_request.value.require_code_owner_review + require_last_push_approval = pull_request.value.require_last_push_approval + required_review_thread_resolution = pull_request.value.required_review_thread_resolution + } + } + + dynamic "required_status_checks" { + for_each = var.ruleset.rules.required_status_checks[*] + content { + strict_required_status_checks_policy = required_status_checks.value.strict + dynamic "required_check" { + for_each = toset(required_status_checks.value.contexts) + content { + context = required_check.value + } + } + } + } + } +} diff --git a/modules/github_org/modules/ruleset/outputs.tf b/modules/github_org/modules/ruleset/outputs.tf new file mode 100644 index 0000000..e8cde93 --- /dev/null +++ b/modules/github_org/modules/ruleset/outputs.tf @@ -0,0 +1,3 @@ +output "ruleset" { + value = github_repository_ruleset.this +} diff --git a/modules/github_org/modules/ruleset/terraform.tf b/modules/github_org/modules/ruleset/terraform.tf new file mode 100644 index 0000000..96e79de --- /dev/null +++ b/modules/github_org/modules/ruleset/terraform.tf @@ -0,0 +1,9 @@ +terraform { + required_version = ">= 1.10" + required_providers { + github = { + source = "integrations/github" + version = "6.13.0" + } + } +} diff --git a/modules/github_org/modules/ruleset/variables.tf b/modules/github_org/modules/ruleset/variables.tf new file mode 100644 index 0000000..a6b1c31 --- /dev/null +++ b/modules/github_org/modules/ruleset/variables.tf @@ -0,0 +1,32 @@ +variable "repository" { + type = string +} + +variable "ruleset" { + type = object({ + name = string + target = string + enforcement = string + conditions = object({ + ref_name = object({ + include = list(string) + exclude = list(string) + }) + }) + rules = object({ + deletion = bool + non_fast_forward = bool + pull_request = object({ + required_approving_review_count = number + dismiss_stale_reviews_on_push = bool + require_code_owner_review = bool + require_last_push_approval = bool + required_review_thread_resolution = bool + }) + required_status_checks = object({ + contexts = list(string) + strict = bool + }) + }) + }) +} diff --git a/modules/github_org/modules/team/main.tf b/modules/github_org/modules/team/main.tf new file mode 100644 index 0000000..6a0d9f3 --- /dev/null +++ b/modules/github_org/modules/team/main.tf @@ -0,0 +1,16 @@ +resource "github_team" "this" { + name = var.name + description = var.description + privacy = var.privacy +} + +resource "github_team_membership" "this" { + for_each = merge( + { for u in var.members : u => "member" }, + { for u in var.maintainers : u => "maintainer" }, + ) + + team_id = github_team.this.id + username = each.key + role = each.value +} diff --git a/modules/github_org/modules/team/outputs.tf b/modules/github_org/modules/team/outputs.tf new file mode 100644 index 0000000..62296af --- /dev/null +++ b/modules/github_org/modules/team/outputs.tf @@ -0,0 +1,11 @@ +output "id" { + value = github_team.this.id +} + +output "slug" { + value = github_team.this.slug +} + +output "membership" { + value = github_team_membership.this +} diff --git a/modules/github_org/modules/team/terraform.tf b/modules/github_org/modules/team/terraform.tf new file mode 100644 index 0000000..96e79de --- /dev/null +++ b/modules/github_org/modules/team/terraform.tf @@ -0,0 +1,9 @@ +terraform { + required_version = ">= 1.10" + required_providers { + github = { + source = "integrations/github" + version = "6.13.0" + } + } +} diff --git a/modules/github_org/modules/team/variables.tf b/modules/github_org/modules/team/variables.tf new file mode 100644 index 0000000..b614f9b --- /dev/null +++ b/modules/github_org/modules/team/variables.tf @@ -0,0 +1,23 @@ +variable "name" { + type = string +} + +variable "description" { + type = string + default = "" +} + +variable "privacy" { + type = string + default = "closed" +} + +variable "maintainers" { + type = list(string) + default = [] +} + +variable "members" { + type = list(string) + default = [] +} diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index 0d7d4fc..e71ba18 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -24,36 +24,36 @@ run "public_repo_defaults" { } assert { - condition = github_repository_file.codeowners[".github"].content == "* @IUCLabs/maintainers-slug @carol\n" + condition = module.repository[".github"].codeowners.content == "* @IUCLabs/maintainers-slug @carol\n" error_message = "CODEOWNERS must list maintainers, teams by owner-qualified slug" } assert { - condition = local.repository_access[".github"] == { "@maintainers" = "maintain", carol = "maintain", dave = "push" } + condition = module.repository[".github"].access == { "@maintainers" = "maintain", carol = "maintain", dave = "push" } error_message = "maintainers get maintain (winning over codeowners), codeowners get push" } assert { - condition = keys(github_repository_ruleset.this) == [".github/branch-protection", ".github/tag-protection"] && length(github_team_membership.this) == 2 + condition = keys(module.repository[".github"].rulesets) == ["branch-protection", "tag-protection"] && length(module.team["maintainers"].membership) == 2 error_message = "public repo must get only the generated branch-protection and tag-protection rulesets" } assert { condition = ( - github_repository_ruleset.this[".github/tag-protection"].target == "tag" && - github_repository_ruleset.this[".github/tag-protection"].enforcement == "active" && - github_repository_ruleset.this[".github/tag-protection"].conditions[0].ref_name[0].include == tolist(["refs/tags/v*"]) && - github_repository_ruleset.this[".github/tag-protection"].rules[0].deletion && - github_repository_ruleset.this[".github/tag-protection"].rules[0].non_fast_forward + module.repository[".github"].rulesets["tag-protection"].target == "tag" && + module.repository[".github"].rulesets["tag-protection"].enforcement == "active" && + module.repository[".github"].rulesets["tag-protection"].conditions[0].ref_name[0].include == tolist(["refs/tags/v*"]) && + module.repository[".github"].rulesets["tag-protection"].rules[0].deletion && + module.repository[".github"].rulesets["tag-protection"].rules[0].non_fast_forward ) error_message = "tag-protection ruleset must make refs/tags/v* undeletable and immutable" } assert { condition = ( - github_repository.this[".github"].allow_squash_merge && - !github_repository.this[".github"].allow_merge_commit && - !github_repository.this[".github"].allow_rebase_merge + module.repository[".github"].repository.allow_squash_merge && + !module.repository[".github"].repository.allow_merge_commit && + !module.repository[".github"].repository.allow_rebase_merge ) error_message = "merge_type defaults to squash only" } @@ -69,7 +69,7 @@ run "private_repo_defaults" { } assert { - condition = length(github_repository_ruleset.this) == 0 && length(github_repository_file.codeowners) == 1 + condition = length(module.repository["secret"].rulesets) == 0 && module.repository["secret"].codeowners != null error_message = "private repo defaults to no rulesets but still gets CODEOWNERS" } } @@ -86,8 +86,8 @@ run "merge_type_rebase" { assert { condition = ( - github_repository.this["r"].allow_rebase_merge && !github_repository.this["r"].allow_squash_merge && !github_repository.this["r"].allow_merge_commit && - github_repository.this["m"].allow_merge_commit && !github_repository.this["m"].allow_squash_merge && !github_repository.this["m"].allow_rebase_merge + module.repository["r"].repository.allow_rebase_merge && !module.repository["r"].repository.allow_squash_merge && !module.repository["r"].repository.allow_merge_commit && + module.repository["m"].repository.allow_merge_commit && !module.repository["m"].repository.allow_squash_merge && !module.repository["m"].repository.allow_rebase_merge ) error_message = "merge_type must enable exactly the matching allow_* flag" } @@ -115,17 +115,17 @@ run "generated_and_custom_rulesets" { } assert { - condition = toset(keys(github_repository_ruleset.this)) == toset(["checked/required-checks", "checked/signed"]) + condition = toset(keys(module.repository["checked"].rulesets)) == toset(["required-checks", "signed"]) error_message = "required_checks with protections off yields only required-checks plus custom rulesets" } assert { - condition = github_repository_ruleset.this["checked/required-checks"].rules[0].required_status_checks[0].strict_required_status_checks_policy + condition = module.repository["checked"].rulesets["required-checks"].rules[0].required_status_checks[0].strict_required_status_checks_policy error_message = "required-checks ruleset must be strict" } assert { - condition = length(github_repository_ruleset.this["checked/required-checks"].rules[0].pull_request) == 0 + condition = length(module.repository["checked"].rulesets["required-checks"].rules[0].pull_request) == 0 error_message = "required-checks ruleset must not carry pull_request rules" } } @@ -152,7 +152,7 @@ run "public_tag_protection_only" { } assert { - condition = keys(github_repository_ruleset.this) == ["tags/tag-protection"] + condition = keys(module.repository["tags"].rulesets) == ["tag-protection"] error_message = "tag_protection defaults on for public repos independently of branch_protection" } } @@ -242,15 +242,15 @@ run "non_main_default_branch_renamed" { assert { condition = ( - github_branch_default.this["legacy"].branch == "master" && - github_branch_default.this["legacy"].rename && - github_branch_default.this["legacy"].wait_for_rename + module.repository["legacy"].branch_default.branch == "master" && + module.repository["legacy"].branch_default.rename && + module.repository["legacy"].branch_default.wait_for_rename ) error_message = "default_branch must rename the auto-init main and wait for it to propagate" } assert { - condition = github_repository_file.codeowners["legacy"].branch == "master" + condition = module.repository["legacy"].codeowners.branch == "master" error_message = "CODEOWNERS must be committed to the renamed default branch" } } From e62c3246eaaace84d7f9ea978a75f8f982b0635a Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Tue, 10 Nov 2026 22:41:00 +1100 Subject: [PATCH 9/9] reject repository references to undefined teams --- modules/github_org/modules/team/outputs.tf | 4 ---- modules/github_org/tests/github_org.tftest.hcl | 12 ++++++++++++ modules/github_org/variables.tf | 5 +++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/modules/github_org/modules/team/outputs.tf b/modules/github_org/modules/team/outputs.tf index 62296af..d3df79f 100644 --- a/modules/github_org/modules/team/outputs.tf +++ b/modules/github_org/modules/team/outputs.tf @@ -1,7 +1,3 @@ -output "id" { - value = github_team.this.id -} - output "slug" { value = github_team.this.slug } diff --git a/modules/github_org/tests/github_org.tftest.hcl b/modules/github_org/tests/github_org.tftest.hcl index e71ba18..b1ffc78 100644 --- a/modules/github_org/tests/github_org.tftest.hcl +++ b/modules/github_org/tests/github_org.tftest.hcl @@ -231,6 +231,18 @@ run "unknown_ruleset_rejected" { expect_failures = [var.repository] } +run "unknown_team_rejected" { + command = plan + + variables { + repository = { + public = { name = "public", codeowners = ["@missing"] } + } + } + + expect_failures = [var.repository] +} + run "non_main_default_branch_renamed" { command = plan diff --git a/modules/github_org/variables.tf b/modules/github_org/variables.tf index 4781959..b487c5c 100644 --- a/modules/github_org/variables.tf +++ b/modules/github_org/variables.tf @@ -108,4 +108,9 @@ variable "repository" { condition = alltrue(flatten([for repo in var.repository : [for rs in repo.rulesets : contains(keys(var.ruleset), rs)]])) error_message = "Unknown rulesets referenced: ${join(", ", distinct(flatten([for name, repo in var.repository : [for rs in repo.rulesets : "${name}/${rs}" if !contains(keys(var.ruleset), rs)]])))}." } + + validation { + condition = alltrue(flatten([for repo in var.repository : [for e in concat(repo.maintainers, repo.codeowners) : contains(keys(var.team), trimprefix(e, "@")) if startswith(e, "@")]])) + error_message = "Unknown teams referenced: ${join(", ", distinct(flatten([for name, repo in var.repository : [for e in concat(repo.maintainers, repo.codeowners) : "${name}/${e}" if startswith(e, "@") && !contains(keys(var.team), trimprefix(e, "@"))]])))}." + } }