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])}." + } +}