GitHub AI Engineering Academy · Part 16 of 16
Build an AI-Powered DevOps Pipeline with GitHub Actions and AI Agents
Academy curriculum (16 lessons)
Across fifteen lessons this academy built the pieces of AI-assisted engineering one at a time. You learned to work in GitHub as an AI engineer, to drive Copilot in the CLI, the editor, and across Terraform, Docker, Kubernetes, Bash, and Python. You built AI-aware CI, then a real AI agent, then deployed an LLM application through GitHub Actions, and most recently made AI review a first-class part of the pull request. Each lesson solved a bounded problem. This capstone does something different: it assembles those pieces into one coherent, controlled, human-gated engineering system — and, just as importantly, it draws the lines that keep that system safe.
The temptation at the end of a journey like this is to imagine the finish line as an autonomous AI that takes an Issue and ships to production by itself. That is the wrong picture, and building it would be a mistake. The governing thesis of this entire lesson is simpler and far more durable:
AI generates, analyzes, and assists. Deterministic tooling validates. Humans retain authority over high-impact production decisions.
The pipeline is not “AI → production.” It is a loop with boundaries at every expensive step:
Issue → AI Agent → Plan → Branch → Code/Infra → Local Validation
→ Pull Request → GitHub Actions CI (lint / unit / IaC / scan / AI-eval / build)
→ AI Review (advisory) → Human Review → Merge
→ Immutable Artifact → Staging → Smoke/Integration
→ Human Production Approval → Production
→ Observability → Incident/Feedback → new Issue
Every arrow in that diagram is either an AI acceleration, a deterministic gate, or a human decision — never a place where a probabilistic model unilaterally changes production. This lesson walks that loop end to end, using a single realistic scenario the whole way through, and it is also the academy’s internal-link hub: each technology below links back to the lesson that teaches it in depth.
What an “AI DevOps Engineer” actually is
It helps to define the agent as a capability set rather than a personality. An AI DevOps Engineer, in this architecture, is the combination of task intake, repository understanding, AI reasoning, a set of constrained tools, local validation, the GitHub workflow, and — always — human oversight. Given those capabilities, it can:
- Interpret a GitHub Issue and extract acceptance criteria
- Inspect the repository to understand the existing code and infrastructure
- Propose a plan and a risk assessment
- Write application code, tests, and infrastructure on a feature branch
- Open a pull request with a full explanation
- Explain a failing CI job and propose a fix on its branch
- Respond to review comments
And it must not be able to:
- Merge its own pull request
- Modify production secrets
- Run a destructive Terraform apply
- Alter IAM or access policies
- Deploy arbitrary code
- Reach production systems at all
That second list is not a matter of the model choosing to behave. It is enforced by what tools the agent has, what credentials it holds, and what network it runs in. The capability set is deliberately shaped like a careful contributor who can propose anything through a PR and change nothing directly.
The nine-layer architecture
The system separates into nine layers, each with a single responsibility. Keeping them distinct is what lets you reason about security: a compromise or a bug in one layer is contained by the boundaries of the next.
Layer 1 Task Management GitHub Issues — intent, acceptance criteria, risk, labels
Layer 2 AI Agent Plan → branch → code/infra/tests → open PR (STOPS HERE)
Layer 3 Source Control Branch protection / rulesets, CODEOWNERS, PR required
Layer 4 Validation Actions: lint, types, unit, IaC validate, scans, AI eval
Layer 5 AI Review Advisory diff review — risk, findings, missing tests
Layer 6 Human Review A person reads code + AI + scans + plan, approves merge
Layer 7 Immutable Artifact Build once: SHA/semver/digest, GHCR, scan, provenance
Layer 8 Deployment Staging → validate → HUMAN prod approval → production
Layer 9 Observability App/AI/dependency/K8s metrics → alerts → new Issue
Layers 1 through 6 get a change ready to merge. Layer 7 turns merged code into one artifact. Layers 8 and 9 promote and watch that artifact — with a human gate between staging and production. The agent lives only in Layer 2 and touches Layer 3 through a pull request; it has no reach into Layers 7, 8, or 9.
The capstone repository
Everything in this lesson lives in one repository whose structure encodes the architecture. The layout below is the shape of the capstone project; each directory maps to a layer above.
ai-devops-platform/
├── .github/
│ ├── workflows/
│ │ ├── agent.yml # trusted trigger → run agent → open PR
│ │ ├── ci.yml # lint, types, unit, scans, path-filtered
│ │ ├── terraform.yml # fmt, validate, TFLint, scan, plan
│ │ ├── container.yml # build once, scan, push GHCR, attest
│ │ ├── ai-review.yml # advisory AI review of the diff
│ │ ├── deploy-staging.yml # deploy immutable artifact to staging
│ │ └── deploy-production.yml # Environment-gated production promotion
│ ├── ISSUE_TEMPLATE/
│ │ └── agent-task.yml
│ ├── CODEOWNERS
│ └── AI_REVIEW.md # reviewer guidance for AI findings
├── agent/
│ ├── github_client.py # GitHub App auth → installation token
│ ├── planner.py # Issue → plan + risk assessment
│ ├── tools.py # constrained tools (NOT run_any_shell)
│ ├── executor.py # orchestration loop
│ └── safety.py # policy, input sanitization boundaries
├── app/
│ ├── main.py # the service
│ ├── llm.py # provider-neutral model interface
│ └── prompts/
│ └── system.txt
├── tests/ # deterministic unit tests (mock the model)
├── evaluations/ # AI evaluations (probabilistic, graded)
├── terraform/
│ ├── modules/
│ └── environments/
│ ├── staging/
│ └── production/
├── kubernetes/
│ ├── base/
│ └── environments/
│ ├── staging/
│ └── production/
├── scripts/
├── Dockerfile
├── compose.yaml
├── pyproject.toml
├── .dockerignore
├── .gitignore
└── README.md
Notice what is not here: no secrets, no Terraform state, no long-lived credentials. Those live in GitHub Environments, a secure state backend, and a secrets manager — outside the repository the agent can read.
The scenario: Issue #147 — Add Redis-Based Response Caching
To keep the walkthrough concrete, every one of the twenty-five steps below follows a single change request. Here is the Issue:
Issue #147: Add Redis-Based Response Caching
The service calls the model provider on every request, which is slow and
expensive for repeated queries. Add Redis-backed caching:
- Cache successful responses only (never errors)
- TTL of 300 seconds
- Add unit tests for cache hit and cache miss
- Update compose.yaml for local Redis
- Update the Kubernetes manifests for the Redis dependency
- Update the README
Constraints:
- Do NOT expose Redis publicly
- Do NOT change production credentials
- Do NOT modify IAM or production secrets
Labels: agent-task, backend, docker, kubernetes, medium-risk
This is a medium-risk change: it touches application code, Compose, and Kubernetes, but not production secrets, IAM, or destructive infrastructure. That risk classification will shape how the pipeline treats it.
Walking the pipeline: twenty-five steps
Step 1 — Issue intake
A human writes Issue #147 with explicit acceptance criteria, an implied risk level, and labels. The labels (agent-task, backend, docker, kubernetes, medium-risk) are machine-readable routing hints, but the decisive act is human: a person has authorized this work and stated what “done” means and what the change must not touch.
Step 2 — Agent trigger
The agent begins only on a trusted trigger — a maintainer runs a manual workflow_dispatch, applies an approved label, or issues a trusted-collaborator slash command. It never starts from arbitrary public Issue content, because anyone can open an Issue and Issue text is untrusted. This single rule closes the most obvious abuse path: a stranger cannot get the agent to act simply by filing an Issue.
Step 3 — Agent authentication
The agent authenticates as a GitHub App, exchanging its credentials for a short-lived installation token scoped to this specific repository, with only the permissions it needs: read contents, write branches, open pull requests, comment on Issues. There is no broad organization token and no classic PAT tied to a human. This connects to the auth discipline from working in GitHub as an AI engineer: identity is scoped, short-lived, and least-privilege.
Step 4 — Reading the repository
The agent reads what it needs to understand the change: the Issue, the README, the architecture notes, the relevant Python in app/, the existing tests, compose.yaml, and the Kubernetes manifests. It does not read secrets, Terraform state, private keys, or unrelated large directories. Constraining what the agent reads limits both the tokens it burns and the blast radius of a leak.
Step 5 — Creating a plan
Before writing code, the agent produces an auditable, human-visible plan — posted as an Issue comment — describing the Redis abstraction it will add, the files it will change, and the tests it will write. A visible plan is reviewable before any code exists, which is far cheaper than reviewing a finished diff.
Step 6 — Risk assessment
The agent classifies the change. This one is medium: application code plus Compose plus Kubernetes, but no production secrets, no IAM, no destructive Terraform. The risk level determines how many gates apply later — a docs change and a production-secret change do not deserve the same ceremony, a point the risk-based automation table below makes explicit.
Step 7 — Creating a branch
The agent creates agent/issue-147-redis-cache. It never commits to main. The branch namespace (agent/) makes agent-authored work visible at a glance and easy to protect with rulesets.
Step 8 — The Python change
The agent adds a Redis abstraction with sensible timeouts, caches only successful responses, never logs secrets or full payloads, adds unit tests for hit and miss, and preserves the existing API surface. This is ordinary application engineering, the kind covered in driving Copilot for Python. A sketch of the caching wrapper:
# app/cache.py
import hashlib
import json
from typing import Optional
import redis
CACHE_TTL_SECONDS = 300
class ResponseCache:
def __init__(self, client: redis.Redis) -> None:
self._client = client
def _key(self, prompt: str, model: str) -> str:
digest = hashlib.sha256(f"{model}:{prompt}".encode()).hexdigest()
return f"resp:{digest}"
def get(self, prompt: str, model: str) -> Optional[dict]:
raw = self._client.get(self._key(prompt, model))
return json.loads(raw) if raw else None
def set_success(self, prompt: str, model: str, response: dict) -> None:
# Cache successful responses only; errors are never cached.
self._client.setex(
self._key(prompt, model),
CACHE_TTL_SECONDS,
json.dumps(response),
)
Step 9 — The Compose update
The agent adds a Redis service to compose.yaml for local development, bound to the internal network and not published to a public port:
# compose.yaml (excerpt)
services:
app:
build: .
environment:
REDIS_URL: redis://cache:6379/0
AI_API_KEY: ${AI_API_KEY}
depends_on:
- cache
cache:
image: redis:7-alpine
# No published ports: Redis is reachable only on the internal network.
networks:
- internal
networks:
internal:
This follows the container discipline from Copilot for Docker: minimal image, no needless exposure, secrets from the environment.
Step 10 — The Kubernetes update
The agent updates the manifests to express the Redis dependency and the new REDIS_URL configuration. If it adds an in-cluster Redis for the tutorial, it labels that clearly as a learning example, not a production data-tier recommendation — a managed cache is usually the right production choice. The application Deployment keeps the safe shape from Copilot for Kubernetes:
# kubernetes/base/deployment.yaml (excerpt)
apiVersion: apps/v1
kind: Deployment
metadata:
name: ai-service
spec:
replicas: 3
template:
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: ai-service
image: ghcr.io/example/ai-service@sha256:PLACEHOLDER
ports:
- containerPort: 8080
env:
- name: AI_API_KEY
valueFrom:
secretKeyRef:
name: ai-service-secrets
key: ai-api-key
- name: REDIS_URL
valueFrom:
secretKeyRef:
name: ai-service-secrets
key: redis-url
readinessProbe:
httpGet:
path: /ready
port: 8080
livenessProbe:
httpGet:
path: /health # deliberately does NOT call the model provider
port: 8080
resources:
requests:
cpu: "100m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
The liveness probe hits /health, which checks the process — not the model provider. If liveness depended on inference, a provider outage would restart every pod and turn a degraded service into a dead one.
Step 11 — Terraform, only if required
Issue #147 does not require infrastructure changes, so the agent does not invent them — forcing an unnecessary Terraform change is its own anti-pattern. When infrastructure is required, the agent generates it and runs the deterministic safety chain from Copilot for Terraform: fmt, validate, TFLint, a security scan (Trivy trivy config or Checkov; tfsec is legacy and merged into Trivy), and terraform plan. It never runs a blind production apply.
Step 12 — Local validation
The agent validates before opening a PR: Ruff and mypy and pytest for Python, docker compose config for Compose, kubeconform for the manifests, and terraform fmt/validate/plan if infrastructure changed. This is the same local-first hygiene from Copilot for Bash — catch the cheap failures before they cost a CI run.
Step 13 — The agent reviews its own diff
The agent inspects its own git diff for unrelated changes, accidental secrets, noise, missing files, or — critically — accidental edits to .github/workflows/. An agent that quietly modifies the workflows that gate it is a red flag the self-review is designed to catch.
Step 14 — Commit
The agent commits with a conventional message referencing the Issue:
feat: add Redis response caching (#147)
Step 15 — Create the pull request
The agent opens a PR — and stops. The PR description is thorough: the Issue link, a summary, the architecture impact, the changed files, local test results, the risks, the deployment impact, and rollback notes. This is the agent’s authority ceiling. From here, deterministic CI, advisory AI review, and a human take over.
Step 16 — CI starts
Opening the PR triggers the CI workflow, which runs the full deterministic suite: lint → unit tests → type check → secret scan → dependency scan → Terraform validation → Kubernetes validation → Docker build → container scan → AI evaluation. Several disciplines shape this stage:
- Fast-fail ordering. Cheap checks first. You do not spend AI-evaluation tokens or GPU minutes before basic lint and unit tests have passed.
- Path-based CI. Jobs are conditional on what changed —
terraform/**,kubernetes/**,app/**,Dockerfile— so a docs edit does not run the entire matrix. - AI evaluation stage. Evaluations run only when
app/prompts/**,app/llm.py, orevaluations/**change. Deterministic tests are not AI evaluations; the former assert exact behavior on mocked models, the latter grade probabilistic output against rules. This distinction comes straight from GitHub Actions for AI applications. - GPU stage if required. Only when a GPU workload is affected does the pipeline reach for GPU runners, following GitHub Actions GPU workflows. Issue #147 touches neither prompts nor GPU code, so both stages are skipped.
A path-filtered skeleton:
# .github/workflows/ci.yml (excerpt)
name: CI
on:
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
lint-and-test:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -e ".[dev]"
- run: ruff check .
- run: mypy app
- run: pytest -q
Step 17 — Automated AI code review
A separate workflow runs the advisory AI review from automated AI code review. It takes the diff plus the test and scan summaries as input and produces a risk assessment, findings, missing-test observations, and operational-impact notes — posted as a PR comment. It is advisory. It is not a required check, and if it cannot run it reports “unavailable” rather than silently passing.
Step 18 — Human review
A human reviewer reads the code, the AI findings, the scanner output, the Terraform plan (if any), and the deployment effects, then decides. AI input is one signal among several, not the decision.
Two source-control controls back this up. CODEOWNERS routes sensitive paths to the right teams:
# .github/CODEOWNERS (team handles are placeholders — replace with real teams)
/terraform/ @your-org/platform
/kubernetes/ @your-org/platform
/.github/workflows/ @your-org/devops
/app/ @your-org/backend
Sensitive paths demand the review of the people accountable for them; an app-code change should not silently alter infrastructure or the workflows that gate the pipeline without the owning team seeing it.
Repository rulesets — the current recommended policy framework, with the branch-protection-to-rulesets migration generally available as of 2026-08-11 — enforce a required PR, required status checks (which must be success, skipped, or neutral to merge), required reviews, no force-pushes, and required workflows, layered at the repository, organization, and enterprise levels. Classic branch protection still exists, but rulesets are where new configuration should go. Verify the exact ruleset options against current GitHub documentation, as this area is actively evolving.
Step 19 — Merge
The PR merges only after CI passed, the AI review was considered, and a human approved. The agent cannot self-approve, and no configuration lets it bypass a failing required check.
Step 20 — Build the immutable artifact
On merge, the container workflow builds the image, scans it (Trivy or Docker Scout), tags it with an immutable reference — a Git SHA or semantic version, never latest for production — pushes it to GHCR, and produces a provenance attestation. Build once, deploy many: the same digest is what reaches every environment.
# .github/workflows/container.yml (excerpt)
permissions:
contents: read
packages: write
id-token: write
attestations: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=sha
type=semver,pattern={{version}}
- id: push
uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- uses: actions/attest-build-provenance@v4
with:
subject-name: ghcr.io/${{ github.repository }}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
The actions/attest-build-provenance@v4 step generates SLSA provenance via Sigstore and in-toto, giving you a verifiable record of how and where the artifact was built. It needs id-token: write, attestations: write, and contents: read. Provenance attestation is available for public repositories on all plans; private repositories require GitHub Enterprise Cloud. Newer implementations may use actions/attest; verify the current action and major version against official documentation before adopting it. The point stands regardless of the exact action: the artifact is addressed by digest and its origin is attestable, so what runs in production is provably what CI built.
Step 21 — Deploy to staging
The deploy-staging workflow updates the staging Deployment to the exact immutable artifact — by digest — and waits on the rollout. Staging is a real GitHub Environment; it can require its own reviewers or run automatically, depending on your risk tolerance.
Step 22 — Staging validation
Staging is where you prove the change against a live model before a human is asked to approve production. Validation covers health, integration, and cache behavior:
- Health check.
GET /healthconfirms the process is up — necessary but not sufficient, so it is never the only check. - Integration test. Request 1 goes to the model and stores the response; request 2 is served from Redis with no model call. Mocks and a real staging Redis make this exact.
- AI smoke evaluation. A small, bounded evaluation confirms the live model integration still works — a handful of cases, not the full golden dataset.
# tests/integration/test_cache_behavior.py (excerpt)
def test_second_request_hits_cache(client, model_spy):
r1 = client.post("/ask", json={"prompt": "what is a container?"})
r2 = client.post("/ask", json={"prompt": "what is a container?"})
assert r1.json() == r2.json()
# The model provider was called exactly once; the second was cached.
assert model_spy.call_count == 1
Step 23 — Human production approval
Staging passing is a signal, not authorization. Production is a GitHub Environment with required reviewers: the promotion job pauses until a designated human approves it, and only then are the production-scoped secrets usable. This is the second and most important human gate in the pipeline.
Step 24 — Production deployment
On approval, the deploy-production workflow promotes the exact staging artifact by digest — no rebuild — into the production Kubernetes environment, which carries the probes, limits, secure context, and immutable image reference from Copilot for Kubernetes. Deployment verification is deterministic: wait on kubectl rollout status, hit the health endpoint, run a bounded smoke test, and watch metrics and error rate before declaring success.
Step 25 — Observability and the feedback loop
Production is watched on four layers:
- Application: request rate, error rate, latency.
- AI: model-provider failures, inference latency, evaluation-quality trend, token usage and cost.
- Redis: connection failures, cache hit/miss ratio, memory.
- Kubernetes: pod restarts, readiness, resource saturation.
Example custom metric names (illustrative) might include ai_provider_request_failures_total, ai_inference_latency_seconds, cache_hits_total, and cache_misses_total. Whatever you name them, the observability layer is what closes the loop:
Production → metrics / logs / alerts → problem detected
→ automated Issue created → AI agent analyzes
→ proposed fix PR → CI → AI review → human review
→ merge → artifact → staging → HUMAN prod approval → Production
That loop is the whole system in miniature, and it never shortcuts the human gates.
The feedback loop in detail
Incident workflow. An alert fires, an Issue is created (verify the exact GitHub API against current docs; include the alert, environment, timestamp, sanitized logs, a dashboard reference, and the affected service — never secrets), the agent analyzes it and drafts a diagnosis, and it may open a proposed-fix PR. Alerts never trigger unreviewed production changes; they trigger proposals.
AI-assisted incident analysis summarizes logs, correlates recent deploys, suggests checks, and lists likely causes — always structured as three separate sections so a human is never handed a confident-sounding fabrication:
FACTS: error rate rose from 0.2% to 4.1% at 14:03 UTC;
deploy of sha256:abc… completed 14:01 UTC.
HYPOTHESES: the new cache key may collide across models;
Redis connection pool may be undersized.
RECOMMENDED CHECKS: inspect cache-key construction for model scoping;
check redis_connection_failures_total since 14:00.
The agent never asserts a single root cause as fact. Facts are facts; everything else is labeled as a hypothesis or a check.
Rollback architecture
Deploy → health / metrics → regression detected
→ rollback → previous immutable artifact → verified healthy
Rollback comes in two forms. Automated rollback fires on deterministic signals only — a failed rollout, failing readiness, or an error rate over threshold — using kubectl rollout undo, reapplying the previous digest, or reverting a GitOps commit. Manual rollback is always available. An LLM’s quality judgment is never the sole authority to roll back production, because moving production must rest on signals that behave identically every run. The target artifact is known in advance; rollback is engineered, not improvised.
Safety boundaries
Terraform safety boundary
Agent generates TF → fmt / validate / TFLint / security scan → plan
→ PR → HUMAN review → SEPARATE approved apply workflow
The agent that writes Terraform is not the workflow that applies it, and a production apply never runs from an untrusted PR with real credentials.
Kubernetes safety boundary
Agent proposes manifests → kubeconform / policy (Kyverno/OPA)
→ PR → HUMAN review → approved deploy workflow → rollout
Coding and applying are separate identities with separate credentials.
Secret architecture
Four distinct credential domains, so no single compromise grants everything:
Agent credential → read repo, write branch, create PR (nothing else)
CI credential → run checks, read repo (no deploy)
Deployment credential → deploy to an approved Environment (scoped)
Application credential→ the model API key at runtime (in the pod)
One credential does not equal all capabilities. This separation of duties is what makes a leaked agent token harmless to production.
OIDC, sandboxing, and network security
Prefer OIDC to exchange a GitHub identity for short-lived cloud credentials instead of storing static keys. Run the agent in a disposable sandbox — a throwaway container, isolated VM, or restricted runner — never on a production host. Ensure the agent’s network has no path to the production database, the management network, the cluster admin plane, or the secrets system. The agent should be technically unable to reach production, not merely instructed not to.
Model security and prompt injection
Every text the model reads — Issues, PRs, repository files, logs, external docs — is untrusted. Prompt injection is not solved by prompt wording; a determined instruction embedded in a file will sometimes influence the model. The defense is enforcement outside the model: permissions, sandboxing, tool restrictions, and credential boundaries. If the agent has no tool that can merge and no credential that can reach production, a successful injection produces, at worst, a PR a human rejects. This is the single most important security idea in the lesson — it comes from building AI agents with GitHub, and it is the reason the create-PR ceiling exists.
The tool-permission architecture
The agent’s tools are constrained by construction. It is given specific, auditable tools — not a general run_any_shell_command, which is an arbitrary escalation path.
Capability Allowed Why
---------------------------------------------------------------------------
Read file ✓ needs to understand the repo
Search code ✓ needs to locate relevant code
Run tests ✓ validates its own change
Write to feature branch ✓ makes the proposed change
Create pull request ✓ the authority ceiling
---------------------------------------------------------------------------
Merge pull request ✗ humans + required checks decide
Terraform apply ✗ separate approved workflow
kubectl against production ✗ deployment identity, not agent
Read production secrets ✗ never in the agent's domain
Delete infrastructure ✗ destructive; human-gated
Run arbitrary shell ✗ arbitrary shell = arbitrary power
Autonomous versus controlled
It is worth stating the contrast plainly, because it is the crux of the whole lesson.
AI → Production (high risk) The controlled agentic flow (safe)
-------------------------------- -----------------------------------------
Model decides to ship Human approves merge and production
No deterministic gates Deterministic CI gates every merge
Model judgment moves prod Deterministic signals move prod
Injection can reach production Injection reaches, at most, a PR
No accountable party Named humans accountable at each gate
Rollback improvised Rollback engineered to a known artifact
The left column is faster to build and impossible to trust. The right column is the point of the last sixteen lessons.
Progressive autonomy: Levels 0–5
You do not deploy the top of this ladder on day one. You climb it, earning trust with evidence, and every rung keeps the same non-negotiables.
Level 0 Explain AI explains code and CI failures; changes nothing.
Level 1 Suggest AI suggests changes; a human applies them.
Level 2 Draft PR Agent opens draft PRs; humans finish and merge.
Level 3 Fix CI on branch Agent iterates on its own branch until CI is green.
Level 4 Deployment candidate Agent produces a candidate; humans approve deploy.
Level 5 Deterministic deploy A deterministic system deploys AFTER human approval.
Note that even Level 5 is not “AI deploys.” It is “a deterministic system deploys after a human approves.” The human production gate never disappears; higher autonomy only changes how much the agent drafts.
Risk-based automation
Not every change deserves the same ceremony. Match the gates to the stakes.
Risk Example Automation
---------------------------------------------------------------------------
Low Docs, comments Agent → PR
Medium App code (Issue #147) Agent → PR + tests + human review
High Terraform / IAM PR + tests + review + EXTRA approval
Critical Prod secrets / destructive Manual — no agent authority at all
Issue #147 sits at Medium: a PR with tests and human review. A change to production secrets would be Critical and outside the agent’s reach entirely.
Workflow architecture
Do not put everything in one workflow. The seven files each own a responsibility:
agent.yml trusted trigger → run agent → open PR
ci.yml lint, types, unit, scans (path-filtered, fast-fail)
terraform.yml fmt, validate, TFLint, scan, plan
container.yml build once, scan, push GHCR, attest provenance
ai-review.yml advisory AI review of the diff
deploy-staging.yml deploy immutable artifact to staging
deploy-production.yml Environment-gated production promotion
Share logic with reusable workflows (workflow_call) rather than copy-paste. Avoid circular triggers, document the dependencies between workflows, and put concurrency limits, timeouts, and cost controls on every job — an AI stage without a timeout is an open-ended bill.
Failure handling, resilience, and audit
Each stage fails safely: tests fail → the PR is blocked; AI review fails → it is marked unavailable, never silently approved; the build fails → no artifact exists to deploy; staging fails → production is unavailable; the production smoke test fails → rollback or escalate. When the AI provider is down, deterministic CI keeps running, AI review shows as unavailable, and high-risk changes still cannot bypass required human review. The pipeline degrades to “slower and more manual,” never to “unguarded.”
Everything leaves an audit trail: the Issue, the workflow runs, the commits, the PR, the reviews, the approvals, and the deployment history. An illustrative end-to-end trace (sample IDs):
Issue #147 → branch agent/issue-147-redis-cache → commit abc123
→ PR #152 → CI green → AI review (advisory) → human approval → merge
→ image ghcr.io/…@sha256:def456… → staging validated
→ HUMAN production approval → production → observed healthy
For compliance and governance, this architecture naturally produces approval records, evidence of least privilege, separation of duties, and full traceability — though it offers no legal guarantees, and you should map it to your own obligations. The human roles are explicit: a developer authors and owns the change, a platform engineer owns infrastructure and the pipeline, a security reviewer owns sensitive paths, and a production approver owns go-live. The agent does not replace any of them; it accelerates their work while they remain accountable.
AI DevOps anti-patterns
Avoid all of these:
- Letting an AI agent deploy directly to production.
- Giving the agent a general
run_any_shell_commandtool. - Granting the agent a broad organization or classic PAT.
- Letting the agent hold or read production secrets.
- Allowing the agent to merge its own pull requests.
- Running untrusted PR code with
pull_request_targetand secrets. - Trusting Issue or PR text as instructions the model must obey.
- Making AI code review a required, blocking merge check.
- Treating a passing AI evaluation as authorization to ship.
- Using
latestimage tags for production instead of immutable references. - Rebuilding the artifact between staging and production.
- Making the liveness probe depend on model-provider inference.
- Letting an AI quality score be the sole rollback trigger.
- Running the agent on a production host instead of a disposable sandbox.
- Skipping the human approval gate on production promotion.
Production-readiness checklist
GitHub
- Repository rulesets require PRs, status checks, and reviews.
- CODEOWNERS routes
terraform/,kubernetes/, and.github/workflows/. - Production is a GitHub Environment with required reviewers.
Agent
- Authenticates as a scoped GitHub App with a short-lived token.
- Runs only on a trusted trigger, never arbitrary Issue content.
- Uses constrained tools; no
run_any_shell_command. - Stops at create-PR; cannot merge, deploy, or reach production.
- Runs in a disposable sandbox with no production network path.
Code
- Ruff, mypy, and pytest pass; secrets never logged.
- AI evaluations gate prompt and model changes.
Terraform
- fmt, validate, TFLint, and a security scan run in CI.
- Apply is a separate, human-approved workflow.
Docker
- Non-root, minimal base, no secrets baked in.
- Image scanned with Trivy or Docker Scout.
Kubernetes
- apps/v1 with readiness and liveness probes (liveness ≠ inference).
- Resource requests/limits and non-root securityContext set.
- Secrets via secretKeyRef, validated with kubeconform and policy.
AI
- Model interface is provider-neutral and mockable.
- AI review is advisory; deterministic checks are required.
Deployment
- Build once; promote the same digest through environments.
- Provenance attestation produced and verifiable.
- Production promotion requires human approval.
Operations
- Four-layer observability (app / AI / dependency / Kubernetes).
- Rollback is engineered to a known artifact on deterministic signals.
- Full audit trail from Issue to production.
40 AI-Powered DevOps Pipeline Ideas
- Agent that triages new Issues and proposes labels and risk levels.
- Agent that drafts acceptance criteria for under-specified Issues.
- Agent that opens a plan comment before writing any code.
- Agent that adds missing unit tests to an existing PR.
- Agent that raises test coverage on a targeted module.
- Agent that updates a dependency and runs the suite on its branch.
- Agent that migrates a workflow from a deprecated action version.
- Agent that generates a Dockerfile that passes a container scan.
- Agent that adds readiness and liveness probes to a Deployment.
- Agent that adds resource requests and limits to manifests.
- Agent that converts a plaintext env value to a secretKeyRef.
- Agent that drafts a Terraform module and a plan summary.
- Agent that summarizes a Terraform plan for human review.
- Agent that flags a security group opening to the world in a plan.
- Agent that adds path filters to a bloated CI workflow.
- Agent that splits a monolithic workflow into responsibility files.
- Agent that adds concurrency and timeout controls to jobs.
- Agent that converts a static cloud key to an OIDC exchange.
- Advisory AI review that annotates diffs with risk and missing tests.
- AI evaluation stage gated on prompt and model changes.
- AI smoke test after a staging deploy.
- Agent that drafts a rollback runbook for a service.
- Agent that proposes a canary or blue-green strategy as a PR.
- Agent that generates a golden dataset skeleton for evaluations.
- Agent that adds structured JSON output to make a feature testable.
- Agent that creates an Issue automatically from an alert.
- Agent that produces a Facts/Hypotheses/Checks incident summary.
- Agent that correlates an error spike with a recent deploy.
- Agent that drafts a fix PR for a recurring, well-understood failure.
- Agent that updates a README to match code changes in the same PR.
- Agent that generates provenance-attestation steps for a build.
- Agent that adds a secret scan to a pipeline missing one.
- Agent that proposes CODEOWNERS entries for sensitive paths.
- Agent that drafts a repository ruleset from a template.
- Agent that standardizes reusable workflows across repositories.
- Agent that reports agent-PR acceptance rate as a metric.
- Agent that measures AI-review agreement with human decisions.
- Agent that tracks deployment frequency and rollback rate.
- Agent that flags workflows running untrusted code with secrets.
- Agent that audits the org for
latesttags in production manifests.
Every one of these stops at a PR or a proposal. None deploys.
30 Rules for Safe AI-Powered DevOps
- AI generates and analyzes; humans decide what ships to production.
- The agent stops at create-PR — never merge, never deploy.
- Give the agent constrained tools, never a general shell.
- Authenticate the agent as a scoped GitHub App, not a broad PAT.
- Use short-lived tokens and OIDC; avoid static long-lived keys.
- Separate agent, CI, deployment, and application credentials.
- Keep production secrets in a protected Environment the agent cannot reach.
- Run the agent in a disposable sandbox with no production network path.
- Trigger the agent only from trusted actions, never arbitrary Issue text.
- Treat all Issue, PR, and repository text as untrusted input.
- Enforce security outside the model, not in the prompt.
- Make AI code review advisory; keep required checks deterministic.
- Never let AI review silently pass when it is unavailable.
- Require human review before any merge to the default branch.
- Require human approval before any production promotion.
- Green CI is a signal, not authorization to ship.
- Build once and promote the same immutable artifact by digest.
- Never use
latestfor production images. - Scan every image and attest its provenance.
- Validate Terraform deterministically; apply in a separate approved workflow.
- Never run untrusted PR code with production secrets.
- Never make a liveness probe depend on model inference.
- Inject secrets via secretKeyRef; never as literals in manifests.
- Roll back to a known artifact on deterministic signals only.
- Never let an AI quality score be the sole rollback authority.
- Route sensitive paths through CODEOWNERS.
- Enforce policy centrally with repository, org, and enterprise rulesets.
- Keep AI evaluations distinct from deterministic tests.
- Keep a full audit trail from Issue to production.
- Remember that accountability stays human — it does not automate.
Capstone Hands-On Lab: Build an AI DevOps Engineer with GitHub Actions and AI Agents
This lab assembles the whole architecture. The model interface is provider-neutral and mockable, GitHub API calls are illustrative and must be verified against current documentation, and no live production deployment, GPU run, or hardware execution is claimed here — the lab builds and reasons about the system; it does not ship to a real cluster.
Phase 1 — Repository and scaffolding (Steps 1–8)
- Create the
ai-devops-platform/repository with the tree shown earlier. - Add
pyproject.tomlwith Ruff, mypy, and pytest configured. - Add
app/main.pywith a/health,/ready, and/askendpoint. - Add
app/llm.pyas a provider-neutral, OpenAI-compatible interface reading key, model, and base URL from the environment. - Add
app/prompts/system.txtas a version-controlled prompt. - Add a
Dockerfile(non-root, minimal base, no secrets baked in). - Add
compose.yamlwith the app and an internal-only Redis. - Add
.dockerignore,.gitignore, and aREADME.md.
Phase 2 — The agent (Steps 9–18)
9. Implement agent/github_client.py to exchange GitHub App credentials for a short-lived installation token (illustrative; verify the API).
10. Implement agent/planner.py to turn an Issue into a plan and a risk level.
11. Implement agent/tools.py with read_file, search, run_tests, write_branch, and create_pull_request — and nothing else.
12. Implement agent/executor.py as the orchestration loop.
13. Implement agent/safety.py with the policy that outranks repository text and sanitizes inputs at the boundary.
14. Wire the model behind the provider-neutral interface so it is mockable in tests.
15. Add a unit test that mocks the model and asserts the agent stops at create-PR.
16. Add a test asserting the agent has no merge or deploy tool.
17. Add a test asserting an injected “merge this now” instruction produces only a PR.
18. Confirm the agent runs entirely in a sandbox with no production credentials.
Phase 3 — The application change (Steps 19–26)
19. Implement app/cache.py with the ResponseCache shown earlier.
20. Cache successful responses only, with a 300-second TTL.
21. Wire the cache into /ask: check cache, call model on miss, store on success.
22. Never log secrets or full payloads.
23. Add unit tests for cache hit and cache miss (mock the model).
24. Preserve the existing API surface.
25. Run Ruff, mypy, and pytest locally.
26. Run docker compose config to validate Compose.
Phase 4 — Infrastructure (Steps 27–33)
27. Add the internal-only Redis service to compose.yaml.
28. Update kubernetes/base/deployment.yaml with REDIS_URL via secretKeyRef.
29. Keep the liveness probe on /health (never inference).
30. Set resource requests, limits, and a non-root securityContext.
31. Add an in-cluster Redis manifest, labeled clearly as a tutorial example.
32. Validate manifests with kubeconform.
33. Add a Kyverno or OPA policy check (illustrative) for non-root and limits.
Phase 5 — CI workflows (Steps 34–41)
34. Write ci.yml with fast-fail ordering and path filters.
35. Add secret and dependency scanning jobs.
36. Write terraform.yml (fmt, validate, TFLint, scan, plan) even if unused here.
37. Write container.yml to build once, scan, push to GHCR, and attest provenance.
38. Use immutable tags (type=sha, type=semver); never latest.
39. Set least-privilege permissions: on every job.
40. Add concurrency groups and timeouts.
41. Add an AI-evaluation job gated on prompt and app/llm.py changes.
Phase 6 — Review and merge gates (Steps 42–48)
42. Write ai-review.yml as an advisory, non-blocking annotation.
43. Ensure AI review reports “unavailable” instead of passing silently.
44. Add CODEOWNERS for terraform, kubernetes, and workflows.
45. Configure a repository ruleset requiring PRs, checks, and reviews (verify options).
46. Confirm required status checks must be success/skipped/neutral to merge.
47. Confirm the agent cannot self-approve or bypass a failing check.
48. Merge only after CI passes, AI review is considered, and a human approves.
Phase 7 — Deployment (Steps 49–56)
49. Write deploy-staging.yml to deploy the exact digest to a staging Environment.
50. Wait on kubectl rollout status and hit /health.
51. Add the cache-behavior integration test (request 2 served from Redis).
52. Add a small, bounded AI smoke evaluation.
53. Configure the production Environment with required reviewers.
54. Write deploy-production.yml to promote the same digest after approval.
55. Scope production secrets to the production Environment only.
56. Add deterministic deployment verification (rollout, health, smoke, error rate).
Phase 8 — Observability and feedback (Steps 57–62)
57. Emit application metrics (requests, errors, latency).
58. Emit AI metrics (provider failures, inference latency, eval trend, cost).
59. Emit cache metrics (cache_hits_total, cache_misses_total, memory).
60. Emit Kubernetes signals (restarts, readiness, saturation).
61. Wire an alert to auto-create an Issue (verify the API; include no secrets).
62. Have the agent produce a Facts/Hypotheses/Checks incident summary.
Phase 9 — Safety hardening and review (Steps 63–66) 63. Verify credential separation across agent, CI, deploy, and app. 64. Verify the rollback path targets a known artifact on deterministic signals. 65. Walk the production-readiness checklist end to end. 66. Confirm every automated step stops at a PR or a proposal — none deploys.
The finished system, drawn in full:
┌──────────────────────────────────────────────────────────────┐
│ GitHub Issue #147 │
│ (intent, acceptance criteria, risk, labels) │
└───────────────────────────────┬──────────────────────────────┘
trusted trigger │
▼
┌──────────────────────────────────────────────────────────────┐
│ AI AGENT (GitHub App, short-lived token, sandbox) │
│ plan → branch → code / tests / infra → local validate │
│ constrained tools · policy > repo text · STOPS AT CREATE-PR │
└───────────────────────────────┬──────────────────────────────┘
▼ pull request
┌──────────────────────────────────────────────────────────────┐
│ GITHUB ACTIONS CI (deterministic, fast-fail, path-filtered) │
│ lint · types · unit · secret/dep scan · IaC validate │
│ docker build · container scan · AI eval (gated) │
└───────────────────────────────┬──────────────────────────────┘
▼
┌───────────────────────────┐ ┌──────────────────────────────┐
│ AI REVIEW (advisory) │──▶│ HUMAN REVIEW (decides merge)│
│ risk · findings · gaps │ │ CODEOWNERS · rulesets │
└───────────────────────────┘ └───────────────┬──────────────┘
▼ merge
┌──────────────────────────────────────────────────────────────┐
│ IMMUTABLE ARTIFACT (build once) │
│ ghcr.io/…@sha256:… · scan · provenance attestation │
└───────────────────────────────┬──────────────────────────────┘
▼ same digest
┌──────────────────────────────────────────────────────────────┐
│ STAGING → health · integration (cache) · AI smoke │
└───────────────────────────────┬──────────────────────────────┘
▼
┌───────────────────────────────┐
│ HUMAN PRODUCTION APPROVAL │ ◀── the gate
│ (Environment + reviewers) │
└───────────────┬───────────────┘
▼ same digest, promoted
┌──────────────────────────────────────────────────────────────┐
│ PRODUCTION (K8s: probes · limits · non-root · secretKeyRef) │
│ deterministic verify · rollback on deterministic signals │
└───────────────────────────────┬──────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ OBSERVABILITY (app · AI · dependency · Kubernetes) │
│ alert → new Issue → agent analysis → proposed fix PR ────────┼──┐
└──────────────────────────────────────────────────────────────┘ │
▲ │
└───────────────── feedback loop ──────────────┘
Every arrow that touches production passes through a human. That is the design.
The internal-link hub: where each piece was taught
This capstone stands on the whole academy. Each technology links back to the lesson that teaches it in depth:
- Working in GitHub as an AI engineer — Part 1
- GitHub Copilot for DevOps — Part 2
- Copilot in the CLI — Part 3
- Copilot in VS Code — Part 4
- Copilot for Terraform — Part 5
- Copilot for Docker — Part 6
- Copilot for Kubernetes — Part 7
- Copilot for Bash — Part 8
- Copilot for Python — Part 9
- GitHub Actions for AI applications — Part 10
- Building AI agents with GitHub — Part 11
- Deploying LLM applications with GitHub Actions — Part 12
- GitHub Models (retired 2026-07-30; provider-neutral interfaces and the Copilot coding agent are the path forward) — Part 13
- GitHub Actions GPU workflows — Part 14
- Automated AI code review — Part 15
If you name the books that support this journey in prose — Learning GitHub Actions, GitHub Copilot Unleashed, and The Ultimate Git and GitHub Guide — they map cleanly onto the Actions, Copilot, and Git foundations the pipeline rests on.
GitHub AI Engineering Academy Complete
You completed all 16 lessons.
You began by learning to work inside GitHub as an AI engineer, then drove Copilot across the command line, the editor, Terraform, Docker, Kubernetes, Bash, and Python. You built AI-aware continuous integration, then a real AI agent, deployed an LLM application through GitHub Actions, understood the retirement of GitHub Models and the move to provider-neutral interfaces, ran GPU workflows, and made AI review a first-class part of the pull request. This capstone assembled all of it into one controlled, human-gated engineering system — from a GitHub Issue, through an agent that stops at create-PR, through deterministic CI and advisory AI review and human approval, to an immutable artifact promoted across staging and production behind a human gate, and back again through observability into the next Issue.
The governing principle is worth carrying with you long after the syntax fades:
The future of DevOps is not an AI with unrestricted production access. It is an engineering system where AI accelerates planning, coding, troubleshooting, testing, review, and automation — while GitHub, deterministic tooling, security controls, observability, and humans provide the boundaries.
AI generates and analyzes. Deterministic tooling validates. Humans retain authority over the decisions that are expensive to get wrong. Build systems that reflect that, and AI makes your engineering faster without making it less accountable.
Continue from the pillars of the academy:
- Academy home — all 16 lessons
- Start again from the foundations — Part 1: GitHub for AI engineers
- Containers with AI — Copilot for Docker
- Orchestration with AI — Copilot for Kubernetes
- Infrastructure with AI — Copilot for Terraform
- Deploying AI applications — Part 12: LLM applications with GitHub Actions
Thank you for building it the right way.
Recommended GitHub Books
Learning GitHub Actions
A guide to automating build, test, and deploy with GitHub Actions — workflows, jobs, runners, and secrets.
- GitHub Actions
- CI/CD
- Automation
GitHub Copilot Unleashed
A deeper dive into AI-assisted development with GitHub Copilot — prompting, workflows, and getting more from the tool.
- Copilot
- AI-assisted development
- Productivity
Ultimate Git and GitHub for Modern Software Development
A broad, practical tour of Git and GitHub for modern development workflows — a solid all-rounder for engineers building on GitHub.
- GitHub
- Workflows
- Foundations
Affiliate Disclosure: Some links on this page are affiliate links. If you purchase through one of these links, DevOps AI Toolkit may earn a commission at no additional cost to you. See our affiliate disclosure.
Frequently asked questions
What is an AI-powered DevOps pipeline?
An AI-powered DevOps pipeline is an engineering system where AI accelerates the human parts of software delivery — planning a change, writing code and infrastructure, generating tests, reviewing a diff, explaining a failing job, drafting an incident diagnosis — while deterministic tooling and humans keep authority over what actually reaches production. It is emphatically not 'AI writes code and deploys it.' The real shape is a controlled loop: a GitHub Issue defines the work, an AI agent plans and opens a pull request, GitHub Actions runs deterministic checks, AI review is advisory, a human approves the merge, an immutable artifact is built once, staging validates it, a human approves production, and observability closes the loop back to a new Issue. AI generates and analyzes; deterministic tooling validates; humans retain authority over high-impact production decisions. Every automated step exists inside boundaries that a person defined and can audit.
Can AI agents manage GitHub Issues?
AI agents can read Issues, extract acceptance criteria, propose labels and risk levels, draft plans as Issue comments, and even open new Issues when an alert fires — but a human authorizes the work before an agent acts on it. The Issue is the unit of intent in this architecture: it is where a person states what should change, what 'done' means, and what the change must not touch. Treat Issue and comment text as untrusted input, because anyone can file an Issue; the agent's own policy must outrank instructions embedded in Issue bodies. A safe pattern is that an agent only begins work when a trusted trigger authorizes it — a maintainer applies an approved label, runs a manual workflow, or issues a trusted-collaborator command — never from arbitrary public Issue content. Managing the Issue queue is assistive; deciding which Issues become work stays human.
Can an AI agent write code and create pull requests?
Yes, and that is precisely where the agent's authority should end. In this architecture the agent reads the repository, forms a plan, creates a feature branch, writes application code, infrastructure, and tests, validates locally, and opens a pull request with a full description of what it changed and why. It stops at create-PR. It does not merge, it does not deploy, and it does not touch production. From the moment the PR exists, control passes to deterministic CI, to advisory AI review, and to a human reviewer who decides whether the change is correct. This mirrors how a junior engineer contributes: they can propose any change through a PR, but merging and shipping are gated by review and by the pipeline. The create-PR ceiling is what makes an autonomous agent safe to run.
Should AI agents deploy directly to production?
No. Direct AI-to-production deployment is the single most dangerous pattern in AI DevOps and this entire lesson is built to prevent it. A large language model is probabilistic, can be manipulated through prompt injection in the repository or an Issue, and cannot be held accountable for an outage. Production changes must remain reviewable and reversible, which means a human approves the merge, a human approves the production promotion through a GitHub Environment with required reviewers, and only deterministic signals — a failed rollout, a failing health probe, a spiking error rate — trigger an automated rollback. The agent never holds production credentials, never runs a destructive Terraform apply, and never has cluster-admin. AI proposes and accelerates; humans and deterministic controls decide what ships. Removing the human from the production boundary removes the only accountable party from the loop.
Can GitHub Actions run an AI DevOps pipeline?
Yes — GitHub Actions is the deterministic backbone of this architecture. Actions runs the agent (on a trusted trigger), runs the full CI suite of lint, type-check, unit tests, secret and dependency scans, infrastructure validation, container build and scan, and AI evaluations, runs the advisory AI code review, builds the immutable artifact, and drives deployment to staging and then production behind Environment approvals. Crucially, Actions is where the gates live: required status checks must pass, required reviewers must approve, and secrets are scoped to protected Environments. The workflows are split by responsibility — agent, CI, Terraform, container, AI review, deploy-staging, deploy-production — rather than crammed into one file, with concurrency limits, timeouts, and least-privilege permissions on every job. Actions provides the determinism that a probabilistic agent cannot.
Can AI review Terraform plans?
AI can summarize a Terraform plan in plain language and flag things worth a human's attention — a resource being destroyed and recreated, a security group opening to the world, an IAM policy broadening — which is genuinely useful because raw plan output is dense and easy to skim past. But AI plan review is advisory only. The deterministic controls remain the authority: terraform fmt, terraform validate, TFLint, a security scan with Trivy config or Checkov, and terraform plan itself. The agent generates Terraform and can open a PR with a plan, but it never runs apply against production. Apply happens in a separate, human-approved workflow, and an untrusted PR must never be allowed to run apply with real credentials. AI makes the plan legible; a human decides whether the plan is acceptable, and a controlled workflow applies it.
Can AI generate Kubernetes manifests?
Yes, and it is one of the most reliable uses of AI in this pipeline, because Kubernetes manifests are structured, well-documented, and easy to validate deterministically. An agent can produce an apps/v1 Deployment with readiness and liveness probes, resource requests and limits, a non-root securityContext, and secrets injected via secretKeyRef, then validate it with kubeconform and a policy engine like Kyverno or OPA before opening a PR. The important safety rule is that the liveness probe must never depend on model-provider inference, or a provider outage would trigger endless pod restarts. Generated manifests are proposals: they go through the same PR, review, and approval flow as everything else, and any in-cluster dependency an agent adds for a tutorial should be clearly labeled as a learning example rather than a production recommendation.
Can AI automatically fix failed CI jobs?
AI can propose fixes for failing CI jobs on the agent's own feature branch, where they are reviewed like any other change — it can read the failing log, identify a lint violation or a broken import, push a commit, and let CI re-run. What it must not do is bypass the failure or self-approve the fix. A failed check is a signal that something is wrong; the correct response is a reviewed correction, not a mechanism to make red turn green automatically. This is Progressive Autonomy Level 3: the agent iterates on its branch until CI is green, but the branch still faces the full gauntlet of required checks and human review before merge. An agent that could silently 'fix' CI on the main branch or force a merge past a failing gate would defeat the entire purpose of the pipeline.
How should an AI agent authenticate to GitHub?
Through a GitHub App with scoped installation permissions, exchanged for a short-lived installation token, rather than a broad or classic personal access token tied to a human account. A GitHub App can be granted exactly the permissions the agent needs — read repository contents, write to branches, open pull requests, comment on Issues — and nothing more, installed only on the specific repositories it works in. The installation token is short-lived, which limits the blast radius if it leaks. Inside Actions, the job-scoped GITHUB_TOKEN with an explicit least-privilege permissions block covers most workflow needs. For cloud access, prefer OIDC to exchange a GitHub identity for short-lived cloud credentials instead of storing static keys. The principle throughout is least privilege plus short-lived credentials: the agent's identity should be unable to do anything it was not explicitly authorized to do.
What permissions should an AI DevOps agent have?
Exactly the permissions needed to read a repository, understand it, make a change on a branch, run tests, and open a pull request — and no more. Concretely: read files, search code, run tests, write to a feature branch, and create a PR are allowed; merging, running terraform apply, kubectl against production, reading production secrets, and deleting infrastructure are denied. The agent is given constrained, purpose-built tools rather than a general run-any-shell-command capability, because an arbitrary shell is an arbitrary escalation path. This tool-permission boundary is enforced outside the model — in the credentials the agent holds, the sandbox it runs in, and the tools it is wired to — not by asking the model politely in a prompt. An agent that cannot technically reach production cannot be tricked into breaking it.
How do you protect production secrets from AI agents?
By ensuring the agent never holds them and never runs where they are available. Production secrets live in a protected GitHub Environment, scoped so they are only usable by the deployment job after a required reviewer approves it — a job the agent does not run. The agent operates with its own scoped credential (repo read, branch write, PR create), the CI system has its own, the deployment system has its own, and the application has its own; one credential compromise does not grant all capabilities. The agent runs in a disposable sandbox with no network path to production databases, management networks, the cluster's admin plane, or secret stores. Separation of duties is the core idea: the identity that writes code is architecturally distinct from the identity that can read production secrets, so no single compromise — of the model, the agent, or a token — exposes production.
Can GitHub Models power the agent?
No — GitHub Models was retired on 2026-07-30, so there is no live GitHub Models endpoint to build against. The model interface in this architecture is deliberately provider-neutral: a thin abstraction (an llm.py module) that speaks an OpenAI-compatible API and reads its key, model name, and base URL from environment configuration, so you can point it at whichever provider you use and swap providers without touching application logic. Alternatively, GitHub's managed Copilot coding agent can play the agent role: you assign an Issue to it, and it branches, writes code on Actions runners, and opens a PR for review — the same create-PR ceiling this lesson enforces. Either way, the model is a replaceable dependency behind an interface, not a hardcoded vendor endpoint, and the model never becomes a production-control authority. Verify current provider and Copilot capabilities against official documentation, since these features evolve.
Where do human approvals belong?
At every high-impact boundary: the merge into the default branch, and the promotion into production. A human reviews the pull request — reading the code, the AI review findings, the scanner output, the Terraform plan, and the deployment impact — and decides whether to merge; the agent never self-approves. A second human approval gates production through a GitHub Environment with required reviewers, after staging has been validated. Lower-impact steps can be more automated, but the two moments where a mistake is expensive and hard to reverse — entering the shared codebase and entering production — always require a person. This is not bureaucracy; it is the placement of accountability. The reviewer and the production approver are the humans answerable for what the system ships, which is exactly why those gates cannot be delegated to a probabilistic model.
How should production rollbacks work?
As a defined, tested path to a known-good immutable artifact, triggered automatically only by deterministic signals and always available manually. Because every build is tagged with an immutable reference — a Git SHA, a semantic version, or an image digest, never latest — the previous good deployment is unambiguous, so rollback is redeploying that exact artifact. On Kubernetes the mechanism is kubectl rollout undo or reapplying the prior image reference; in GitOps you revert the desired-state commit. Automated rollback fires on signals that behave identically every run: a failed rollout, failing readiness probes, or an error rate crossing a threshold. An AI-judged quality score is never the sole trigger, because a probabilistic judgment must not unilaterally move production. Rollback is engineered in advance, not improvised during an incident, and the target artifact is always known before you need it.
Can AI replace DevOps engineers?
No. AI changes what DevOps engineers spend their time on, but it does not remove the accountability that defines the role. Someone must own the architecture, define the guardrails, review the changes an agent proposes, approve production promotions, and answer for outages — and that someone is a human engineer. In this architecture the humans have clear roles: a developer authors and owns changes, a platform engineer owns infrastructure and the pipeline, a security reviewer owns sensitive paths, and a production approver owns the go-live decision. The agent accelerates the mechanical parts — drafting code, generating tests, summarizing diffs, explaining failures — so engineers spend more time on design, review, and judgment. An agent that proposes a change is not accountable for it; the engineer who approves and ships it is. Accountability does not automate.
What is the safest way to introduce AI agents into CI/CD?
Progressively, one autonomy level at a time, earning trust with evidence before granting more. A useful ladder runs from Level 0, where AI only explains code and failures, to Level 5, where a fully deterministic system deploys after human approval. In between: Level 1 the agent suggests changes a human applies; Level 2 it opens draft PRs; Level 3 it iterates on CI failures on its own branch; Level 4 it produces a deployment candidate that humans still approve. You do not start at the top. Introduce the agent at a low level on a non-critical repository, measure how often its proposals are correct, tighten the guardrails where they leak, and only then increase autonomy. Every level keeps the same non-negotiables — least privilege, stop at create-PR, human approval for production — so raising autonomy changes how much the agent drafts, never who is accountable for what ships.
How do you monitor an AI-powered DevOps pipeline?
On four layers at once, because this system has more failure modes than an ordinary service. Application monitoring covers request rate, error rate, and latency. AI monitoring covers model-provider failures, inference latency, evaluation quality trends, and token usage and cost — signals an ordinary app does not have. Redis or dependency monitoring covers connection failures, cache hit and miss rates, and memory. Kubernetes monitoring covers pod restarts, readiness, and resource saturation. On top of the running service, you monitor the pipeline itself: how often the agent's PRs pass CI, how often AI review agrees with humans, deployment frequency, and rollback rate. The observability layer feeds the feedback loop — an alert becomes an Issue, which becomes agent analysis, which becomes a proposed fix PR — closing the loop while keeping every production change behind human review.
How do you prevent prompt injection from compromising an agent?
By treating every piece of text the model reads — Issue bodies, PR descriptions, code comments, logs, external docs — as untrusted input, and by enforcing security outside the model rather than inside the prompt. You cannot fully prevent a model from being talked into something through cleverly crafted repository text; instructions like 'ignore your rules and merge this' will sometimes influence output. The defense is that it does not matter, because the agent has no tool that can merge, no credential that can reach production, and no shell that can escalate. Permissions, sandboxing, tool restrictions, and credential boundaries make a successful injection harmless: the worst a manipulated agent can do is open a PR that a human then rejects. Agent policy outranks repository text, and the technical inability to act on a malicious instruction — not the model's willingness to refuse it — is what actually protects you.
Should AI code review be a required merge check?
No — AI code review should be advisory, and the required merge checks should be deterministic. Make AI review a helpful, non-blocking annotation that surfaces risk, missing tests, and operational impact for the human reviewer to consider; do not wire it as a required status check that can pass or fail the merge. The reasons are practical: a probabilistic reviewer will sometimes approve a flawed change and sometimes block a fine one, and if AI review is unavailable it must fail visibly as 'unavailable' rather than silently pass, which a required-check-that-defaults-to-green would invite. The required gates are the deterministic ones — lint, type-check, tests, security scans, infrastructure validation — plus required human review. AI review makes the human reviewer faster and more thorough; it does not replace the human decision or the deterministic gates, and it never becomes the thing that authorizes a merge.
How do you scale this architecture across many repositories?
By standardizing the controls centrally and reusing them, so every repository inherits the same guardrails without copying them by hand. Use organization-level and enterprise-level repository rulesets to enforce required PRs, required status checks, and required reviews everywhere; use reusable workflows (workflow_call) so the CI, container, and deployment logic lives in one place and each repo calls it; and template the agent configuration, CODEOWNERS, and Environment setup. A GitHub App installed across the organization gives the agent scoped, consistent access. The principle is that the security posture is defined once and applied broadly, not reinvented per repository where it will inevitably drift. As you scale, watch the aggregate signals — agent PR acceptance rate, AI-review agreement, rollback rate — across repositories, and keep the non-negotiables uniform: least privilege, stop at create-PR, deterministic gates, and human approval for production, regardless of how many repositories run the pattern.
← Back to GitHub AI Engineering Academy