manage IUCLabs GitHub organisation #118

Merged
benvin merged 9 commits from benvin/github-iuclabs into main 2026-11-10 22:49:21 +11:00
25 changed files with 977 additions and 41 deletions
+1
View File
@@ -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
+40 -16
View File
@@ -1,12 +1,14 @@
.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
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..."
@@ -50,3 +68,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)'
+48 -1
View File
@@ -1,3 +1,50 @@
# terraform-git
Manage Gitea resources, teams, repos, and Woodpecker CI via Terraform
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.
`modules/github_org` validates config and calls `modules/team` (team + memberships) and `modules/repository` (repo, default branch, collaborators, CODEOWNERS, rulesets via `modules/ruleset`).
`team/<name>.yaml`:
```yaml
description: "IUCLabs maintainers"
privacy: closed
maintainers: [neoloc]
members: []
```
`repository/<name>.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
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/<name>.yaml` (custom extras; `branch-protection`, `required-checks` and `tag-protection` are reserved):
```yaml
target: branch
enforcement: active
conditions:
ref_name:
include: ["refs/heads/release/*"]
exclude: []
rules:
deletion: true
non_fast_forward: true
```
Private repositories cannot use `branch_protection`, `tag_protection`, `required_checks` or `rulesets` on the free plan; plan fails if they do.
+29 -6
View File
@@ -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
}
}
}
@@ -0,0 +1,4 @@
description: "IUCLabs organisation profile"
private: false
maintainers:
- "@maintainers"
@@ -0,0 +1,5 @@
description: "IUCLabs maintainers"
privacy: closed
maintainers:
- neoloc
members: []
+24
View File
@@ -16,6 +16,30 @@ terraform {
source = "../../../modules/gitea_instance"
}
generate "provider" {
path = "provider.tf"
if_exists = "overwrite"
contents = <<EOF
provider "gitea" {
base_url = "https://git.unkin.net"
cacert_file = "/etc/pki/tls/certs/ca-bundle.crt"
}
provider "woodpecker" {
server = "https://ci.k8s.syd1.au.unkin.net"
}
# Address + token come from VAULT_ADDR / VAULT_TOKEN in the environment (the
# Makefile authenticates via k8s auth before running terragrunt). Used to seed
# bot-account credentials into Vault KV (see modules/user vault_seed_path).
# skip_child_token: the CI token from the k8s auth role cannot create child
# tokens (apply fails with "failed to create limited child token").
provider "vault" {
skip_child_token = true
}
EOF
}
inputs = {
organisation = local.config.organisation
repository = local.config.repository
@@ -0,0 +1,36 @@
include "root" {
path = find_in_parent_folders("root.hcl")
expose = true
}
include "config" {
path = "${get_repo_root()}/config/config.hcl"
expose = true
}
locals {
owner = "IUCLabs"
github = include.config.locals.github
}
terraform {
source = "../../../modules/github_org"
}
generate "provider" {
path = "provider.tf"
if_exists = "overwrite"
contents = <<EOF
provider "github" {
owner = "${local.owner}"
app_auth {}
}
EOF
}
inputs = {
owner = local.owner
team = { for k, v in local.github.team : v.name => 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 }
}
-18
View File
@@ -2,24 +2,6 @@ generate "backend" {
path = "backend.tf"
if_exists = "overwrite"
contents = <<EOF
provider "gitea" {
base_url = "https://git.unkin.net"
cacert_file = "/etc/pki/tls/certs/ca-bundle.crt"
}
provider "woodpecker" {
server = "https://ci.k8s.syd1.au.unkin.net"
}
# Address + token come from VAULT_ADDR / VAULT_TOKEN in the environment (the
# Makefile authenticates via k8s auth before running terragrunt). Used to seed
# bot-account credentials into Vault KV (see modules/user vault_seed_path).
# skip_child_token: the CI token from the k8s auth role cannot create child
# tokens (apply fails with "failed to create limited child token").
provider "vault" {
skip_child_token = true
}
terraform {
backend "consul" {
address = "https://consul.service.consul"
+24
View File
@@ -0,0 +1,24 @@
module "team" {
source = "./modules/team"
for_each = var.team
name = each.value.name
description = each.value.description
privacy = each.value.privacy
maintainers = each.value.maintainers
members = each.value.members
}
module "repository" {
source = "./modules/repository"
for_each = var.repository
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, "@")
}
}
@@ -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]
}
@@ -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 }
}
@@ -0,0 +1,9 @@
terraform {
required_version = ">= 1.10"
required_providers {
github = {
source = "integrations/github"
version = "6.13.0"
}
}
}
@@ -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 = {}
}
@@ -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
}
}
}
}
}
}
@@ -0,0 +1,3 @@
output "ruleset" {
value = github_repository_ruleset.this
}
@@ -0,0 +1,9 @@
terraform {
required_version = ">= 1.10"
required_providers {
github = {
source = "integrations/github"
version = "6.13.0"
}
}
}
@@ -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
})
})
})
}
+16
View File
@@ -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
}
@@ -0,0 +1,7 @@
output "slug" {
value = github_team.this.slug
}
output "membership" {
value = github_team_membership.this
}
@@ -0,0 +1,9 @@
terraform {
required_version = ">= 1.10"
required_providers {
github = {
source = "integrations/github"
version = "6.13.0"
}
}
}
@@ -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 = []
}
+9
View File
@@ -0,0 +1,9 @@
terraform {
required_version = ">= 1.10"
required_providers {
github = {
source = "integrations/github"
version = "6.13.0"
}
}
}
@@ -0,0 +1,307 @@
mock_provider "github" {
mock_resource "github_team" {
defaults = { slug = "maintainers-slug" }
}
}
variables {
owner = "IUCLabs"
team = {
maintainers = { name = "maintainers", maintainers = ["alice"], members = ["bob"] }
}
ruleset = {
signed = { name = "signed", rules = { deletion = true, pull_request = {} } }
}
}
run "public_repo_defaults" {
command = plan
variables {
repository = {
".github" = { name = ".github", private = false, maintainers = ["@maintainers", "carol"], codeowners = ["carol", "dave"] }
}
}
assert {
condition = module.repository[".github"].codeowners.content == "* @IUCLabs/maintainers-slug @carol\n"
error_message = "CODEOWNERS must list maintainers, teams by owner-qualified slug"
}
assert {
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(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 = (
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 = (
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"
}
}
run "private_repo_defaults" {
command = plan
variables {
repository = {
secret = { name = "secret", maintainers = ["@maintainers"] }
}
}
assert {
condition = length(module.repository["secret"].rulesets) == 0 && module.repository["secret"].codeowners != null
error_message = "private repo defaults to no rulesets but still gets CODEOWNERS"
}
}
run "merge_type_rebase" {
command = plan
variables {
repository = {
r = { name = "r", merge_type = "rebase" }
m = { name = "m", merge_type = "merge" }
}
}
assert {
condition = (
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"
}
}
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, tag_protection = false, required_checks = ["ci/woodpecker"], rulesets = ["signed"] }
}
}
assert {
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 = 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(module.repository["checked"].rulesets["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 "public_tag_protection_only" {
command = plan
variables {
repository = {
tags = { name = "tags", private = false, branch_protection = false }
}
}
assert {
condition = keys(module.repository["tags"].rulesets) == ["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
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
variables {
repository = {
public = { name = "public", private = false, rulesets = ["missing"] }
}
}
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
variables {
repository = {
legacy = { name = "legacy", default_branch = "master", maintainers = ["carol"] }
}
}
assert {
condition = (
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 = module.repository["legacy"].codeowners.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]
}
+116
View File
@@ -0,0 +1,116 @@
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 = {}
validation {
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" {
description = "Map of repositories to create, keyed by name"
type = map(object({
name = string
description = optional(string, "")
private = optional(bool, true)
default_branch = optional(string, "main")
maintainers = optional(list(string), [])
codeowners = optional(list(string), [])
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), [])
}))
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 && 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])}."
}
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])}."
}
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)]])))}."
}
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, "@"))]])))}."
}
}