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
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,11 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- run: bash tests/action-logic.sh

# tests/drift-issue.sh extracts and runs the real run: block from
# examples/drift-detection.yml via PyYAML, same technique self-lint
# uses for action.yml.
- name: Install PyYAML
run: python3 -m pip install --quiet pyyaml

- run: bash tests/drift-issue.sh
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,10 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
as inputs, not a replacement, setting both fails loud by design. `s3` only,
R2 has no OIDC equivalent. See the README's "OIDC for AWS S3" section for
the trust policy and the required `permissions: id-token: write`.
- Example scheduled drift-detection workflow
(`examples/drift-detection.yml`): calls the action with no `command:`
override, relying on the existing safer default (`plan` for any non-`push`
event) instead of a special drift mode. Opens or updates a single Issue
carrying a `drift-detection` label when `has-changes == 'true'`, instead
of filing a new Issue every run. See the README's "Drift detection"
section.
31 changes: 26 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ is unaffected by this: its `plan` job already gates on
`github.event_name == 'pull_request'` and its `apply` job gates on
`github.event_name == 'push'`, so neither job ever hits the action with any
other event type. This only matters for consumers that call the action
directly from other event types (a scheduled drift check, for example).
directly from other event types (a scheduled drift check, for example, see
[Drift detection](#drift-detection)).

## Policy gate

Expand Down Expand Up @@ -226,6 +227,25 @@ steps:
No `access-key-id`/`secret-access-key` needed, the role is assumed
directly.

## Drift detection

`iac-cicd` has no dedicated "drift" mode, drift detection is just the same
plan/apply primitives run on a schedule. See
[`examples/drift-detection.yml`](examples/drift-detection.yml) for a
complete `on: schedule` (plus `workflow_dispatch` for manual runs) workflow
that calls the action with no `command:` override. Because the triggering
event isn't `push`, the auto-detect default resolves to `plan` (see
[Manual approval before apply](#manual-approval-before-apply)), so a
scheduled run never applies anything on its own, it only reports what's
changed outside the pipeline.

When the action's `has-changes` output is `'true'`, the example's follow-up
step opens or updates a single GitHub Issue instead of filing a new one on
every run. It tags the Issue with a `drift-detection` label and searches
only issues carrying that label for its marker before deciding whether to
`PATCH` an existing Issue or `POST` a new one, so the search stays bounded
instead of scanning every open issue in the repo.

## Inputs

| Input | Required | Default | Description |
Expand Down Expand Up @@ -280,10 +300,11 @@ does not touch that block.

## What this deliberately doesn't do

- No bundled policy engine, no drift detection, no cost estimation.
`policy-command` (see [Policy gate](#policy-gate)) is a hook to your own
policy tool, not a built-in one. If you need drift detection or cost
estimation, look at a full platform (Scalr, Terrakube).
- No bundled policy engine, no cost estimation. `policy-command` (see
[Policy gate](#policy-gate)) is a hook to your own policy tool, not a
built-in one. Drift detection isn't a special mode either, it's the same
plan primitives on a schedule, see [Drift detection](#drift-detection).
If you need cost estimation, look at a full platform (Scalr, Terrakube).
- No generic multi-provider backend abstraction. R2 and AWS S3 are the two
tuned targets; other S3-compatible providers work through the `endpoint`
escape hatch on a best-effort basis, see "Other S3-compatible providers"
Expand Down
81 changes: 81 additions & 0 deletions examples/drift-detection.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Example scheduled drift-detection workflow for zeroconfigio/github-action-iac-cicd.
#
# Runs a daily plan against the state backend and, if it finds changes nobody
# applied through this pipeline (drift), opens or updates a single sticky,
# labeled Issue rather than filing a new one every day. Never applies
# anything: it does not pass `command:` to the action, so the action falls
# back to its own default, `plan` for any event that isn't `push` (see the
# README's "Manual approval before apply" section), the safer choice for an
# unattended schedule.
#
# Required repo secrets: R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET.
# Same four backend secrets as plan-apply.yml, this workflow needs read
# access to the state backend to run its plan.
#
# This example uses the default backend (Cloudflare R2). For AWS S3 (static
# keys or OIDC), see plan-apply.yml's header comment and commented-out
# alternate blocks for the full diff.

name: drift-detection

on:
schedule:
# 06:00 UTC daily.
- cron: "0 6 * * *"
workflow_dispatch:

permissions: {}

concurrency:
group: drift-detection-${{ github.ref }}
cancel-in-progress: false

jobs:
detect:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- id: iac
uses: zeroconfigio/github-action-iac-cicd@v1
with:
account-id: ${{ secrets.R2_ACCOUNT_ID }}
access-key-id: ${{ secrets.R2_ACCESS_KEY_ID }}
secret-access-key: ${{ secrets.R2_SECRET_ACCESS_KEY }}
bucket: ${{ secrets.R2_BUCKET }}

- name: Open or update drift Issue
# This step's environment still carries the backend credentials the
# action exported earlier in the job. Fine while this run: block
# stays static; don't add anything here that shells out based on
# issue/PR-controlled content.
if: steps.iac.outputs.has-changes == 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail

marker="<!-- iac-cicd-drift -->"
repo="${{ github.repository }}"

existing=$(gh api "repos/$repo/issues?labels=drift-detection&state=open" --paginate \
| jq -r --arg marker "$marker" '.[] | select((.body // "") | startswith($marker)) | .number' \
| head -n1)

body_file="$RUNNER_TEMP/drift-issue-body.md"
{
echo "$marker"
echo "Drift detected: the last scheduled plan found changes outside this pipeline."
echo ""
echo "See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
} > "$body_file"

if [ -n "$existing" ]; then
gh api -X PATCH "repos/$repo/issues/$existing" -F body=@"$body_file"
else
gh api -X POST "repos/$repo/issues" -F title="Drift detected" -F body=@"$body_file" -F "labels[]=drift-detection"
fi
194 changes: 194 additions & 0 deletions tests/drift-issue.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
#!/usr/bin/env bash
# Extracts and runs the real run: block from examples/drift-detection.yml's drift-issue step.
set -uo pipefail

failures=0
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
workflow_file="$script_dir/../examples/drift-detection.yml"
work_dir="$(mktemp -d)"
trap 'rm -rf "$work_dir"' EXIT

# ${{ }} expressions are substituted for real shell values at extraction time.
test_repo="octocat/Hello-World"
test_server_url="https://github.example"
test_run_id="4242"

extracted_script="$work_dir/drift-issue-step.sh"

python3 - "$workflow_file" "$extracted_script" "$test_repo" "$test_server_url" "$test_run_id" <<'PY'
import sys

import yaml

workflow_path, out_path, repo, server_url, run_id = sys.argv[1:6]

with open(workflow_path) as f:
workflow = yaml.safe_load(f)

steps = workflow["jobs"]["detect"]["steps"]
step = next(s for s in steps if s.get("name") == "Open or update drift Issue")
script = step["run"]

script = script.replace("${{ github.repository }}", repo)
script = script.replace("${{ github.server_url }}", server_url)
script = script.replace("${{ github.run_id }}", run_id)

if "${{" in script:
sys.stderr.write("unstubbed GitHub Actions expression left in extracted script\n")
sys.exit(1)

with open(out_path, "w") as f:
f.write("#!/usr/bin/env bash\n")
f.write(script)
PY

if [ $? -ne 0 ]; then
echo "FAIL: could not extract the drift-issue step's run: text from $workflow_file"
exit 1
fi

# Pulled from the extracted text, so this stays in sync with the real marker.
marker="$(sed -n 's/^marker="\(.*\)"$/\1/p' "$extracted_script")"

if [ -z "$marker" ]; then
echo "FAIL: could not read the marker value out of the extracted script"
exit 1
fi

# Logs verb+path per line, -F/-f values on their own indented lines below it.
stub_dir="$work_dir/bin"
mkdir -p "$stub_dir"

cat > "$stub_dir/gh" <<'STUB'
#!/usr/bin/env bash
set -euo pipefail

if [ "${1:-}" != "api" ]; then
echo "gh-stub: unsupported subcommand '${1:-}'" >&2
exit 1
fi
shift

verb="GET"
path=""
fields=()

while [ $# -gt 0 ]; do
case "$1" in
-X)
verb="$2"
shift 2
;;
-F|-f)
fields+=("$2")
shift 2
;;
--paginate)
shift
;;
*)
path="$1"
shift
;;
esac
done

echo "$verb $path" >> "$GH_STUB_LOG"
for field in "${fields[@]+"${fields[@]}"}"; do
echo " -F $field" >> "$GH_STUB_LOG"
done

case "$verb" in
GET)
printf '%s' "${GH_STUB_ISSUES_RESPONSE:-[]}"
;;
*)
exit 0
;;
esac
STUB
chmod +x "$stub_dir/gh"

log_file="$work_dir/gh-stub.log"

# Fresh stub log per call, so no scenario depends on another's leftovers.
run_extracted_script() {
local issues_response="$1"

: > "$log_file"

PATH="$stub_dir:$PATH" \
GH_TOKEN="dummy-token" \
RUNNER_TEMP="$work_dir" \
GH_STUB_LOG="$log_file" \
GH_STUB_ISSUES_RESPONSE="$issues_response" \
bash "$extracted_script"
}

# Scenario 1: no existing labeled+marked issue (empty array) creates one via POST, not PATCH.
if run_extracted_script "[]" > /dev/null 2>&1; then
if grep -qx "POST repos/$test_repo/issues" "$log_file" && ! grep -q "^PATCH " "$log_file"; then
echo "PASS: no existing labeled+marked issue results in a POST to create the issue, not a PATCH"
else
echo "FAIL: no existing labeled+marked issue did not POST as expected (log: $(cat "$log_file"))"
failures=$((failures + 1))
fi
if grep -qx " -F labels\[\]=drift-detection" "$log_file"; then
echo "PASS: the created issue carries the drift-detection label"
else
echo "FAIL: the created issue is missing the drift-detection label (log: $(cat "$log_file"))"
failures=$((failures + 1))
fi
else
echo "FAIL: extracted script exited nonzero for the no-existing-issue scenario"
failures=$((failures + 1))
fi

# Scenario 2: an existing labeled+marked issue (number 42) is updated via PATCH, not POST.
existing_issue_response='[{"number": 42, "body": "'"$marker"'\nDrift detected: the last scheduled plan found changes outside this pipeline."}]'

if run_extracted_script "$existing_issue_response" > /dev/null 2>&1; then
if grep -qx "PATCH repos/$test_repo/issues/42" "$log_file" && ! grep -q "^POST " "$log_file"; then
echo "PASS: an existing labeled+marked issue (42) results in a PATCH, not a POST"
else
echo "FAIL: existing labeled+marked issue did not PATCH as expected (log: $(cat "$log_file"))"
failures=$((failures + 1))
fi
else
echo "FAIL: extracted script exited nonzero for the existing-issue scenario"
failures=$((failures + 1))
fi

# A labeled issue with no body (GitHub allows this) must not crash the script.
null_body_response='[{"number": 7, "body": null}]'

if run_extracted_script "$null_body_response" > /dev/null 2>&1; then
if grep -qx "POST repos/$test_repo/issues" "$log_file" && ! grep -q "^PATCH " "$log_file"; then
echo "PASS: a labeled issue with a null body is treated as no match, still POSTs"
else
echo "FAIL: a null-body issue did not fall through to POST as expected (log: $(cat "$log_file"))"
failures=$((failures + 1))
fi
else
echo "FAIL: extracted script crashed on a labeled issue with a null body"
failures=$((failures + 1))
fi

# Scenario 3: has-changes == false is the step's own if:, verified by grep, not execution.
# Scoped to the whole step block, not just the next line, so a comment doesn't break the match.
step_block=$(awk '/name: Open or update drift Issue/{p=1} p{print} p && /run: \|/{exit}' "$workflow_file")

if echo "$step_block" | grep -q "if: steps.iac.outputs.has-changes == 'true'"; then
echo "PASS: the drift-issue step is gated by if: steps.iac.outputs.has-changes == 'true'"
else
echo "FAIL: the drift-issue step is not gated by the expected has-changes if: condition"
failures=$((failures + 1))
fi

if [ "$failures" -gt 0 ]; then
echo "$failures scenario(s) failed"
exit 1
fi

echo "All scenarios passed"
exit 0