From b150c32e0b7f4ff4b135f7e8a124a6c95a3f3c6a Mon Sep 17 00:00:00 2001 From: Ben Birt Date: Sun, 29 Nov 2026 08:23:43 +0000 Subject: [PATCH] Add a reusable OpenTofu workflow, with drift tofu.yml plans a tf_deploy target on pull requests, applies it on main and checks it for drift on a schedule, opening a drift issue and failing when it differs. The Settings workflow becomes its first caller, with the daily drift check that drift.yaml ran, so drift.yaml goes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/drift.yaml | 88 -------------------- .github/workflows/settings.yaml | 55 ++++--------- .github/workflows/tofu.yml | 141 ++++++++++++++++++++++++++++++++ README.md | 70 ++++++++++++++-- 4 files changed, 218 insertions(+), 136 deletions(-) delete mode 100644 .github/workflows/drift.yaml create mode 100644 .github/workflows/tofu.yml diff --git a/.github/workflows/drift.yaml b/.github/workflows/drift.yaml deleted file mode 100644 index 73969c3..0000000 --- a/.github/workflows/drift.yaml +++ /dev/null @@ -1,88 +0,0 @@ -name: Drift - -# Plans github/ daily and on manual runs without taking the state lock, and -# never applies. When GitHub differs from github/, posts the plan on one open -# drift issue and fails the run so GitHub sends a failure notification. On -# scheduled runs, that goes to whoever last changed the schedule. When nothing -# differs, closes any open drift issue. - -on: - schedule: - - cron: "43 6 * * *" - workflow_dispatch: - -permissions: - contents: read - issues: write - -concurrency: - group: settings-drift - -jobs: - drift: - runs-on: ubuntu-latest - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - GITHUB_TOKEN: ${{ secrets.ADMIN_TOKEN }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: R2 keys - run: | - keys=$(tools/r2-keys.sh) - while IFS= read -r line; do - echo "::add-mask::${line#*=}" - echo "$line" >> "$GITHUB_ENV" - done <<<"$keys" - - uses: bazel-contrib/setup-bazel@f34d6a05eae3c24acab7fa54587492daeaeffdab # 0.19.2 - with: - bazelisk-cache: true - disk-cache: ${{ github.workflow }} - repository-cache: true - - name: Plan - id: plan - run: | - # -detailed-exitcode exits 0 when GitHub matches github/ and 2 when - # settings differ. Run under set +e so exit 2 reaches Report; any - # other non-zero code fails the step. - set +e - bazel run --lockfile_mode=error //github:github.plan -- -lock=false -no-color -detailed-exitcode > "$RUNNER_TEMP/plan.txt" - code=$? - set -e - cat "$RUNNER_TEMP/plan.txt" - case "$code" in - 0) echo "drift=false" >> "$GITHUB_OUTPUT" ;; - 2) echo "drift=true" >> "$GITHUB_OUTPUT" ;; - *) exit "$code" ;; - esac - - name: Report - env: - # Use the workflow token for gh; ADMIN_TOKEN is only for the plan. - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - DRIFT: ${{ steps.plan.outputs.drift }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - title="Settings differ from github/" - issue=$(gh issue list --label drift --state open --json number --jq '.[0].number // empty') - if [[ "$DRIFT" == true ]]; then - plan=$(sed -e 's/\x1b\[[0-9;]*m//g' "$RUNNER_TEMP/plan.txt" | - sed -n '/^\(Note: Objects have changed\|OpenTofu used the selected providers\)/,/^Plan:/p' | - head -c 60000) - # The backticks are a Markdown code fence, not a command substitution. - # shellcheck disable=SC2016 - body=$(printf '%s\n\n```\n%s\n```\n\n[Run](%s)\n' \ - "The plan found settings on GitHub that differ from github/. Put the change in github/ or repos.jsonnet to keep it, or run the Settings workflow on main to revert it." \ - "$plan" "$RUN_URL") - gh label create drift --color B60205 --description "Settings differ from github/" --force - if [[ -n "$issue" ]]; then - gh issue comment "$issue" --body "$body" - else - gh issue create --title "$title" --label drift --body "$body" - fi - echo "::error::Settings differ from github/; see the drift issue." - exit 1 - elif [[ -n "$issue" ]]; then - gh issue close "$issue" --comment "No differences in [the latest run]($RUN_URL)." - fi diff --git a/.github/workflows/settings.yaml b/.github/workflows/settings.yaml index 0c3d8b6..df8b9ba 100644 --- a/.github/workflows/settings.yaml +++ b/.github/workflows/settings.yaml @@ -1,8 +1,10 @@ name: Settings -# Plans OpenTofu changes on pull requests without taking the state lock, and -# applies them on pushes to main and manual runs on main, waiting up to 15 -# minutes for the lock. +# Manages //github:github via tofu.yml: plans on pull requests, applies on +# pushes and manual runs on main, and checks for drift daily at 06:43 UTC. +# +# Sets plan_dependabot to false so ADMIN_TOKEN never reaches Dependabot pull +# requests. on: push: @@ -14,6 +16,7 @@ on: - "MODULE.bazel" - "MODULE.bazel.lock" - ".github/workflows/settings.yaml" + - ".github/workflows/tofu.yml" pull_request: paths: - "github/**" @@ -22,47 +25,21 @@ on: - "MODULE.bazel" - "MODULE.bazel.lock" - ".github/workflows/settings.yaml" + - ".github/workflows/tofu.yml" + schedule: + - cron: "43 6 * * *" workflow_dispatch: permissions: contents: read - -# Each pull request plans in its own group and cancels older plans on new -# pushes. Applies share one group and are never cancelled mid-run. -concurrency: - group: settings-${{ github.event_name == 'pull_request' && format('plan-{0}', github.event.pull_request.number) || 'apply' }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + issues: write jobs: settings: - # Skip fork pull requests, which cannot read secrets, and Dependabot pull - # requests, so ADMIN_TOKEN is not given to them. Provider updates are - # applied after they merge. - if: >- - github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]') - runs-on: ubuntu-latest - env: + uses: ./.github/workflows/tofu.yml + with: + target: //github:github + plan_dependabot: false + secrets: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - GITHUB_TOKEN: ${{ secrets.ADMIN_TOKEN }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: R2 keys - run: | - keys=$(tools/r2-keys.sh) - while IFS= read -r line; do - echo "::add-mask::${line#*=}" - echo "$line" >> "$GITHUB_ENV" - done <<<"$keys" - - uses: bazel-contrib/setup-bazel@f34d6a05eae3c24acab7fa54587492daeaeffdab # 0.19.2 - with: - bazelisk-cache: true - disk-cache: ${{ github.workflow }} - repository-cache: true - - name: Plan - if: github.event_name == 'pull_request' - run: bazel run --lockfile_mode=error //github:github.plan -- -lock=false -no-color - - name: Apply - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' - run: bazel run --lockfile_mode=error //github:github.apply -- -lock-timeout=15m -auto-approve -no-color + ADMIN_TOKEN: ${{ secrets.ADMIN_TOKEN }} diff --git a/.github/workflows/tofu.yml b/.github/workflows/tofu.yml new file mode 100644 index 0000000..3b48aa5 --- /dev/null +++ b/.github/workflows/tofu.yml @@ -0,0 +1,141 @@ +name: OpenTofu + +# Plans, applies and checks drift for a rules_tofu tf_deploy target. What runs +# depends on the calling workflow's event: +# +# - pull_request: plans without the state lock. +# - push or workflow_dispatch on main: applies with a 15-minute lock timeout. +# - schedule: plans without the state lock using -detailed-exitcode. On +# differences, it comments on the open drift issue titled +# "Drift: differs from its configuration", opening one if needed, +# and fails the run so GitHub sends a failure notification. Once a scheduled +# run finds no differences, it closes that issue. +# +# The calling repository provides tools/r2-keys.sh to derive R2 S3 keys from +# CLOUDFLARE_API_TOKEN, grants issues: write, chooses the triggering paths and +# sets the schedule. See README.md. + +on: + workflow_call: + inputs: + target: + description: The tf_deploy target to plan and apply, such as //infra:infra. + type: string + required: true + check: + description: >- + A target to bazel run before planning or applying, such as a check of the configuration's inputs. + type: string + default: "" + plan_dependabot: + description: >- + Whether to plan Dependabot pull requests. Planning them requires the same secrets in the repository's Dependabot secrets. + type: boolean + default: true + secrets: + CLOUDFLARE_API_TOKEN: + description: >- + A Cloudflare API token for the R2 state bucket. The calling repository's tools/r2-keys.sh derives S3 keys from it, and the job exports it as CLOUDFLARE_API_TOKEN. + required: true + ADMIN_TOKEN: + description: A GitHub token passed to the github provider as GITHUB_TOKEN. + required: false + POSTHOG_API_KEY: + description: A PostHog API key read by the posthog provider. + required: false + +permissions: + contents: read + issues: write + +jobs: + tofu: + # Skip pull requests from forks, which receive no secrets, and Dependabot + # pull requests when plan_dependabot is false. + if: >- + github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && (inputs.plan_dependabot || github.event.pull_request.user.login != 'dependabot[bot]')) + runs-on: ubuntu-latest + # Scoped per target: each pull request gets its own plan group where a + # newer push cancels an earlier run; drift runs share a group; applies + # share a group so they serialise and are never cancelled. + concurrency: + group: tofu-${{ inputs.target }}-${{ github.event_name == 'pull_request' && format('plan-{0}', github.event.pull_request.number) || github.event_name == 'schedule' && 'drift' || 'apply' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + GITHUB_TOKEN: ${{ secrets.ADMIN_TOKEN }} + POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }} + TARGET: ${{ inputs.target }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: R2 keys + run: | + keys=$(tools/r2-keys.sh) + while IFS= read -r line; do + echo "::add-mask::${line#*=}" + echo "$line" >> "$GITHUB_ENV" + done <<<"$keys" + - uses: bazel-contrib/setup-bazel@f34d6a05eae3c24acab7fa54587492daeaeffdab # 0.19.2 + with: + bazelisk-cache: true + disk-cache: ${{ github.workflow }} + repository-cache: true + - name: Check + if: inputs.check != '' + env: + CHECK: ${{ inputs.check }} + run: bazel run --lockfile_mode=error "$CHECK" + - name: Plan + if: github.event_name == 'pull_request' + run: bazel run --lockfile_mode=error "$TARGET.plan" -- -lock=false -no-color + - name: Apply + if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' + run: bazel run --lockfile_mode=error "$TARGET.apply" -- -lock-timeout=15m -auto-approve -no-color + - name: Drift plan + id: drift + if: github.event_name == 'schedule' + run: | + set +e + bazel run --lockfile_mode=error "$TARGET.plan" -- -lock=false -no-color -detailed-exitcode > "$RUNNER_TEMP/plan.txt" + code=$? + set -e + cat "$RUNNER_TEMP/plan.txt" + case "$code" in + 0) echo "drift=false" >> "$GITHUB_OUTPUT" ;; + 2) echo "drift=true" >> "$GITHUB_OUTPUT" ;; + *) exit "$code" ;; + esac + - name: Report drift + if: github.event_name == 'schedule' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + DRIFT: ${{ steps.drift.outputs.drift }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + title="Drift: $TARGET differs from its configuration" + # $t is a jq variable, not a shell one. + # shellcheck disable=SC2016 + issue=$(gh issue list --label drift --state open --json number,title | + jq -r --arg t "$title" '[.[] | select(.title == $t)][0].number // empty') + if [[ "$DRIFT" == true ]]; then + plan=$(sed -e 's/\x1b\[[0-9;]*m//g' "$RUNNER_TEMP/plan.txt" | + sed -n '/^\(Note: Objects have changed\|OpenTofu used the selected providers\)/,/^Plan:/p' | + head -c 60000) + # shellcheck disable=SC2016 + body=$(printf '%s\n\n```\n%s\n```\n\n[Run](%s)\n' \ + "The scheduled plan of $TARGET found differences from its configuration." \ + "$plan" "$RUN_URL") + gh label create drift --color B60205 --description "Infrastructure differs from its configuration" --force + if [[ -n "$issue" ]]; then + gh issue comment "$issue" --body "$body" + else + gh issue create --title "$title" --label drift --body "$body" + fi + echo "::error::$TARGET differs from its configuration; see the drift issue." + exit 1 + elif [[ -n "$issue" ]]; then + gh issue close "$issue" --comment "No differences in [the latest run]($RUN_URL)." + fi diff --git a/README.md b/README.md index fbd8e1d..a1240e0 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,12 @@ default-branch rulesets and GitHub Pages for every repository under `managed` in `repos.jsonnet`. See [`github/repos.tf`](github/repos.tf) for what is set. Settings change through pull requests editing `repos.jsonnet` or `github/`. -[`settings.yaml`](.github/workflows/settings.yaml) plans on the pull request and -applies on merge to `main`. +[`settings.yaml`](.github/workflows/settings.yaml) calls +[`tofu.yml`](#opentofu) for `//github:github`, planning on pull requests and +applying on pushes and manual runs on `main`. It sets `plan_dependabot: false` +so `ADMIN_TOKEN` never reaches Dependabot pull requests. -The Settings and Drift workflows use two repository secrets: +The Settings workflow uses two repository secrets: - `ADMIN_TOKEN`: a fine-grained personal access token with read and write access to **Administration**, **Contents** and **Pages** on the managed repositories, @@ -34,12 +36,62 @@ The Settings and Drift workflows use two repository secrets: ### Drift -[`drift.yaml`](.github/workflows/drift.yaml) plans `github/` daily and on manual -runs without applying. If settings on GitHub differ from `github/`, it posts the -plan on one open `drift` issue and fails the run so GitHub sends a failure -notification; once a run finds no differences, it closes the issue. Put a change -in `github/` or `repos.jsonnet` to keep it, or run the Settings workflow on -`main` to revert it. +The Settings workflow's schedule runs a drift plan of `//github:github` daily at +06:43 UTC without applying; see [OpenTofu](#opentofu) for how drift issues are +opened and closed. Put a change in `github/` or `repos.jsonnet` to keep it, or +run the Settings workflow manually on `main` to revert it. + +## OpenTofu + +[`tofu.yml`](.github/workflows/tofu.yml) is a reusable workflow for rules_tofu +`tf_deploy` targets. What it runs depends on the calling workflow's event: + +- `pull_request`: runs `.plan` with `-lock=false`. Pull requests from + forks are skipped because they receive no secrets; Dependabot pull requests + are skipped when `plan_dependabot` is `false`. +- `push` or `workflow_dispatch` on `main`: runs `.apply` with + `-auto-approve` and `-lock-timeout=15m`. +- `schedule`: runs `.plan` with `-lock=false -detailed-exitcode`. On + differences, it comments on the open `drift` issue titled + `Drift: differs from its configuration`, opening one if needed, and + fails the run so GitHub sends a failure notification. Once a scheduled run + finds no differences, it closes that issue. + +Concurrency is scoped per `target`: each pull request gets its own plan group +where a newer push cancels an earlier run; drift runs share a group; applies +share a group so they serialise and are never cancelled. + +The calling repository must provide `tools/r2-keys.sh` to derive R2 S3 keys from +`CLOUDFLARE_API_TOKEN`, and its workflow chooses the triggering paths, sets the +schedule and grants `issues: write`: + +```yaml +permissions: + contents: read + issues: write + +jobs: + infra: + uses: benbirt/github-infra/.github/workflows/tofu.yml@ # + with: + target: //infra:infra + secrets: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} +``` + +| Input | Default | Meaning | +| ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- | +| `target` | required | The `tf_deploy` target to plan and apply, such as `//infra:infra`. | +| `check` | none | A target to `bazel run` before planning or applying. | +| `plan_dependabot` | `true` | Whether to plan Dependabot pull requests. Planning them requires the same secrets in the repository's Dependabot secrets. | + +Secrets: + +- `CLOUDFLARE_API_TOKEN` (required): Cloudflare API token for the R2 state + bucket. Passed to `tools/r2-keys.sh` and exported as `CLOUDFLARE_API_TOKEN`. +- `ADMIN_TOKEN` (optional): GitHub token passed to the `github` provider as + `GITHUB_TOKEN`. +- `POSTHOG_API_KEY` (optional): API key read by the `posthog` provider. ## Bazel updates