Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 0 additions & 88 deletions .github/workflows/drift.yaml

This file was deleted.

55 changes: 16 additions & 39 deletions .github/workflows/settings.yaml
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -14,6 +16,7 @@ on:
- "MODULE.bazel"
- "MODULE.bazel.lock"
- ".github/workflows/settings.yaml"
- ".github/workflows/tofu.yml"
pull_request:
paths:
- "github/**"
Expand All @@ -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 }}
141 changes: 141 additions & 0 deletions .github/workflows/tofu.yml
Original file line number Diff line number Diff line change
@@ -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: <target> 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
70 changes: 61 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 `<target>.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 `<target>.apply` with
`-auto-approve` and `-lock-timeout=15m`.
- `schedule`: runs `<target>.plan` with `-lock=false -detailed-exitcode`. On
differences, it comments on the open `drift` issue titled
`Drift: <target> 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@<commit sha> # <tag>
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

Expand Down