CI/CD
Write a GitHub Actions pipeline line by line, then run and debug it.
15 levels · 80 lessons · about 3 hours
CI/CD commands cheat sheet
Every command in the CI/CD Playground, grouped by level. Practise each one above in the interactive terminal.
Show all 80 commandsHide commands
Level 1: Your First Workflow (Beginner)
Write the skeleton of a pipeline that runs on every push.
- Where workflows live
mkdir -p .github/workflowsGitHub Actions looks for workflow YAML files in .github/workflows/. Create that folder first.
- Name the workflow
name: CIEvery workflow starts with a name - it's what you see in the Actions tab.
- Trigger on push
on: pushon: tells GitHub when to run the pipeline. push runs it on every push.
- Pick a runner
runs-on: ubuntu-latestA job runs on a runner - a fresh virtual machine. ubuntu-latest is the most common.
- Check out the code
- uses: actions/checkout@v4The runner starts empty. The checkout action downloads your repository into it.
Level 2: Build & Test (Beginner)
Install dependencies, run tests and cache for speed.
- Set up Node.js
- uses: actions/setup-node@v4setup-node installs a specific Node.js version on the runner.
- Install dependencies
- run: npm cirun: executes a shell command. npm ci is the clean, exact install used in CI.
- Run the tests
- run: npm testIf any command fails, the job fails and the pipeline turns red - that's the point of CI.
- Cache dependencies
cache: npmSetting cache: npm on setup-node reuses downloaded packages between runs, making pipelines much faster.
- Push & trigger it
git pushCommitting and pushing the workflow file is what starts the first run.
Level 3: Run & Debug with gh (Intermediate)
Watch pipelines and read failures from your terminal.
- List recent runs
gh run listgh is GitHub's official CLI. gh run list shows recent workflow runs and their status.
- Watch a run live
gh run watch 9012345678gh run watch follows a run until it finishes.
- Read the failed logs
gh run view 9012345678 --log-failed--log-failed prints only the logs of the steps that failed - the fastest way to find the error.
- Re-run after a fix
gh run rerun 9012345678gh run rerun starts the same run again - handy for flaky tests or after fixing a secret.
- Trigger manually
gh workflow run deploy.ymlWorkflows with on: workflow_dispatch can be started by hand with gh workflow run.
Level 4: Ship to Production (Intermediate)
Use secrets, build images and deploy safely.
- Store a secret
gh secret set DOCKERHUB_TOKENNever put passwords in YAML. gh secret set stores them encrypted in the repo settings.
- Use the secret
password: ${{ secrets.DOCKERHUB_TOKEN }}Inside a workflow, secrets are read with ${{ secrets.NAME }} and are masked in logs.
- Only deploy from main
if: github.ref == 'refs/heads/main'An if: condition stops a job from running on other branches.
- Deploy after tests pass
needs: buildneeds: makes a job wait for another job to succeed first.
- Require approval
environment: productionA GitHub environment can require a reviewer to approve before the deploy job starts.
Level 5: Pro Pipelines (Intermediate)
Run on pull requests, test many versions, save artifacts and avoid clashing deploys.
- Run on pull requests
on: pull_requestpull_request runs the pipeline when a PR is opened or updated, so code is tested before it's merged.
- Test many versions
node-version: [18, 20, 22]A matrix runs the same job several times with different values, e.g. three Node versions in parallel.
- Stop stuck jobs
timeout-minutes: 10timeout-minutes kills a job that hangs, instead of burning minutes for up to 6 hours.
- Save build output
- uses: actions/upload-artifact@v4Artifacts keep files from a run (test reports, build folders) so you can download them or use them in later jobs.
- One deploy at a time
concurrency: productionconcurrency puts runs in a named group. Only one run per group goes at a time, so two deploys never clash.
- Nightly builds
- cron: '0 2 * * *'schedule runs a workflow on a cron timer (in UTC). '0 2 * * *' means every day at 02:00.
Level 6: Docker in the Pipeline (Advanced)
Build a Docker image in CI and push it to a registry on every merge.
- Log in to the registry
- uses: docker/login-action@v3The docker/login-action logs the runner in to Docker Hub or another registry, using a secret.
- Build and push the image
- uses: docker/build-push-action@v6docker/build-push-action builds the Dockerfile and pushes the image, with layer caching.
- Turn pushing on
push: trueBy default the action only builds. push: true sends the image to the registry.
- Tag with the commit
tags: akops/myapp:${{ github.sha }}Tagging images with the Git commit SHA means you always know exactly which code is in an image. github.sha holds it.
- Least-privilege token
contents: readpermissions limits what the pipeline's GITHUB_TOKEN can do. Reading the code is enough for most build jobs.
Level 7: Deploy to Kubernetes (Advanced)
Write a deploy workflow that updates a Kubernetes cluster and checks the rollout.
- Start a deploy by hand
on: workflow_dispatchworkflow_dispatch adds a 'Run workflow' button, so you can deploy when you choose.
- Store the cluster access
gh secret set KUBECONFIG < kubeconfigThe pipeline needs a kubeconfig to talk to the cluster. Store it as a secret, never in the repository.
- Install kubectl on the runner
- uses: azure/setup-kubectl@v4azure/setup-kubectl installs kubectl on the runner, whatever cloud you use.
- Apply the manifests
- run: kubectl apply -f k8s/kubectl apply -f k8s/ applies every YAML file in the k8s folder: deployments, services and so on.
- Fail if the rollout fails
- run: kubectl rollout status deployment/webrollout status waits until the new pods are ready and fails the job if they are not, so a broken deploy turns the pipeline red.
Level 8: Reusable & Secure Pipelines (Advanced)
Share pipelines across repositories, use cloud access without keys and scan for vulnerabilities.
- Make a workflow reusable
on: workflow_callon: workflow_call lets other workflows call this one like a function, so many repos share one tested pipeline.
- Call the reusable workflow
uses: ./.github/workflows/build.ymlA job can use a whole workflow instead of steps.
- Allow cloud login without keys
id-token: writeOIDC lets GitHub prove who it is to AWS, Azure or GCP, so you store no long-lived access keys. It needs the id-token permission.
- Assume an AWS role
- uses: aws-actions/configure-aws-credentials@v4aws-actions/configure-aws-credentials uses the OIDC token to assume an IAM role. The job then has short-lived AWS credentials.
- Scan the image for vulnerabilities
- uses: aquasecurity/trivy-action@0.28.0Trivy scans images for known vulnerabilities. Failing the build on critical findings stops unsafe images reaching production.
Level 9: Faster Pipelines (Advanced)
Cut pipeline time with caching and smart matrix settings.
- Cache dependencies
- uses: actions/cache@v4actions/cache saves a folder between runs, so dependencies don't download every time.
- What to cache
path: ~/.npmnpm keeps downloaded packages in ~/.npm.
- When to refresh it
key: npm-${{ hashFiles('package-lock.json') }}The key decides when the cache is reused. hashFiles changes the key whenever the lock file changes.
- Fall back to an older cache
restore-keys: npm-If there's no exact match, restore-keys uses the newest cache that starts with npm-. Partly warm beats cold.
- Let all matrix jobs finish
fail-fast: falseBy default one failing matrix job cancels the rest. fail-fast: false lets you see every failure at once.
Level 10: Conditions & Outputs (Advanced)
Run steps only when needed, and pass values between steps and jobs.
- Run only on push
if: github.event_name == 'push'github.event_name tells you what started the workflow.
- Run when something failed
if: failure()failure() is true only if an earlier step failed. Use it for alerts and debug dumps.
- Always run
if: always()always() runs even after failures or cancellation. Use it for cleanup and uploading test reports.
- Set an output
- run: echo "version=1.2.0" >> "$GITHUB_OUTPUT"Write name=value to the file in $GITHUB_OUTPUT, and later steps can read it.
- Read the output
VERSION: ${{ steps.meta.outputs.version }}steps.<id>.outputs.<name> reads an output from an earlier step.
- Don't fail the job
continue-on-error: truecontinue-on-error lets an optional step fail without failing the pipeline.
Level 11: Environments & Approvals (Expert)
Deploy to staging, then to production after a human approves it.
- Deploy to staging
environment: stagingAn environment groups secrets and protection rules. GitHub shows deployments per environment.
- Link to the site
url: https://staging.akopslabs.comurl shows a 'View deployment' link on the run.
- Wait for two jobs
needs: [test, build]needs can list several jobs. This job starts only when all of them pass.
- Set a variable for the repo
gh variable set APP_ENV --body stagingVariables are like secrets but not hidden: environment names, regions, URLs.
- Use the variable
APP_ENV: ${{ vars.APP_ENV }}vars.<NAME> reads a variable in the workflow.
- Approve a production deploy
gh run list --workflow=deploy.ymlWith required reviewers on the production environment, the run waits. You approve in the GitHub UI or check its status here.
Level 12: Quality Gates (Expert)
Stop bad code before merge: lint, dependency audit, SonarQube and CodeQL.
- Lint the code
- run: npm run lintA linter catches bugs and style problems in seconds. Run it first, it's the cheapest check.
- Audit dependencies
- run: npm audit --audit-level=highnpm audit checks your packages for known vulnerabilities. --audit-level=high fails only on high and critical.
- Scan with SonarQube
- uses: SonarSource/sonarqube-scan-action@v5SonarQube finds bugs, code smells, duplicate code and security hotspots, and checks your quality gate.
- Give it the token
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}The scanner needs a token and your SonarQube server URL, both from secrets.
- Wait for the quality gate
- uses: SonarSource/sonarqube-quality-gate-action@v1The quality gate action fails the pipeline if the code doesn't meet the gate (e.g. coverage under 80%).
- Turn on CodeQL
- uses: github/codeql-action/init@v3CodeQL is GitHub's free security scanner for public repos.
Level 13: Alerts & ChatOps (Expert)
Send pipeline results to Slack so the team knows straight away.
- Store the Slack webhook
gh secret set SLACK_WEBHOOK_URLAn incoming webhook URL lets anything post to one Slack channel. Treat it like a password.
- Add the Slack step
- uses: slackapi/slack-github-action@v2slackapi/slack-github-action posts a message from the workflow.
- Point it at the webhook
webhook: ${{ secrets.SLACK_WEBHOOK_URL }}The action reads the webhook from the secret.
- Only alert on failure
if: failure()Nobody wants a message for every green build.
- Post from any script
curl -X POST -H 'Content-type: application/json' --data '{"text":"Deploy done"}' $SLACK_WEBHOOK_URLA webhook is just an HTTP POST with JSON, so any script or cron job can alert Slack too.
Level 14: Self-Hosted Runners (Expert)
Run jobs on your own servers when you need private networks, GPUs or more power.
- Download the runner
tar xzf actions-runner.tar.gzA self-hosted runner is a small agent on your server that picks up jobs from GitHub.
- Register it
./config.sh --url https://github.com/akopslabs/demo --token ABC123config.sh connects the runner to your repo with a one-time token from Settings → Actions → Runners.
- Run it as a service
sudo ./svc.sh installsvc.sh installs the runner as a systemd service, so it survives reboots.
- Use your runner
runs-on: [self-hosted, linux, x64]Labels pick the runner. Self-hosted runners always have the self-hosted label.
- Test on Linux and Windows
os: [ubuntu-latest, windows-latest]A matrix over os runs the same job on several operating systems.
Level 15: GitOps with Argo CD (Expert)
Let Argo CD deploy from Git: the repo is the truth, the cluster follows it.
- Log in to Argo CD
argocd login argocd.akopslabs.comArgo CD runs in the cluster and keeps it in sync with a Git repo.
- Create an app
argocd app create web --repo https://github.com/akopslabs/gitops.git --path apps/web --dest-server https://kubernetes.default.svc --dest-namespace webAn Argo CD application links a folder in Git to a namespace in a cluster.
- Sync it
argocd app sync webSync applies what's in Git to the cluster. Turn on auto-sync and every merge deploys itself.
- Check its status
argocd app get webget shows whether the cluster matches Git (Synced) and whether the app works (Healthy).
- See past deployments
argocd app history webEvery sync is recorded with its Git commit.
- Roll back
argocd app rollback web 2If a release is bad, roll back to an earlier sync. Then fix Git, or the next sync brings the bad version back.