# Basic CI/CD structure with GitHub Actions

A Bitflow Solutions guide. Web version: https://bitflow-solutions.com/en/guias-tecnicas/github-actions-ci-cd/

## What you’ll learn

- The parts of a GitHub Actions workflow and where the file goes.
- Continuous integration: running the tests on every push and every pull request.
- Building a Docker image and publishing it to GitHub Container Registry.
- Continuous deployment to a protected environment, with its secrets.
- Protecting the main branch so that nothing is merged without passing the tests.

## Prerequisites

- A repository on **GitHub** where you have admin permissions.
- A project with tests and a `Dockerfile`. We use the one from the *How to build a REST API with FastAPI on Windows* guide.
- For deployment: a Kubernetes cluster with a `Deployment` called `tasks-api` and its kubeconfig (see the Kubernetes administration guide). If you don’t have one yet, you can do steps 1 to 4.
- Knowing how to commit and push with git.

## Step by step

### Parts of a workflow

| Key | What it is for |
|---|---|
| name | Name of the workflow |
| on | What triggers it (push, pull_request, workflow_dispatch, schedule) |
| jobs | Jobs (in parallel by default) |
| runs-on | The job’s machine |
| steps | Steps: uses (action) or run (commands) |
| with / env | Parameters / variables |
| needs / if | Dependencies / conditions |
| secrets | Protected values |
| environment | Environment with its own secrets and rules |
| permissions | GITHUB_TOKEN permissions |

### Location

```text
tasks-api/
├── .github/
│   └── workflows/
│       └── ci-cd.yml
├── main.py
├── test_main.py
├── requirements.txt
└── Dockerfile
```

### Secrets

- Settings > Environments > production > KUBECONFIG secret (complete kubeconfig file)
- Never in the YAML or printed in a step

### Complete workflow (.github/workflows/ci-cd.yml)

```yaml
name: CI/CD

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:

# Minimum permissions by default; each job asks for what it needs
permissions:
  contents: read

# If a new push arrives on the same branch, the previous run is cancelled
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  IMAGE: ghcr.io/company/tasks-api   # always in lowercase

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: Install dependencies
        run: pip install -r requirements.txt pytest

      - name: Run the tests
        run: pytest

  image:
    needs: tests
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push the image
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: ${{ env.IMAGE }}:${{ github.sha }}

  deploy:
    needs: image
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Configure kubectl
        run: |
          mkdir -p ~/.kube
          echo "${{ secrets.KUBECONFIG }}" > ~/.kube/config

      - name: Deploy the new image
        run: |
          kubectl set image deployment/tasks-api api=${{ env.IMAGE }}:${{ github.sha }}
          kubectl rollout status deployment/tasks-api --timeout=120s
```

### Protect main

Settings > Rules > Rulesets: require a pull request and the “tests” check.

## Common errors

- **The workflow does not run**: The file must be in `.github/workflows/` and on the branch of the event. For `workflow_dispatch` (the *Run workflow* button), the file must already be on the main branch.
- **Syntax error in the YAML**: It is almost always the indentation: YAML uses spaces, never tabs, and each level must be aligned. The Actions tab highlights the line with the error.
- **“denied: permission_denied” when publishing to ghcr.io**: The job’s `permissions` are missing `packages: write`, or the package already exists and is not linked to the repository. Check the package’s permissions in *Packages → Package settings*.
- **“repository name must be lowercase”**: Image names in a container registry are in lowercase. If you use `${{ github.repository }}` and the user or organisation has capital letters, write the name by hand in lowercase.
- **Secrets arrive empty in a pull request**: For security, pull requests that come from a fork do not receive secrets. That is why the image and deployment jobs only run on `push`.
- **The required reviewers option does not appear**: Manual approval for environments (*Required reviewers*) is only available on public repositories or with paid plans. With the free plan and a private repository, restrict the environment to the `main` branch or trigger the deployment manually with `workflow_dispatch`.
- **kubectl cannot connect to the cluster**: The `KUBECONFIG` secret must contain the complete file, with its line breaks. Also check that the cluster accepts connections from GitHub’s runners (public IPs) or use your own runner inside your network.

## Next steps

- Add static and security code analysis (for example, SonarCloud or CodeQL) as another job.
- Enable Dependabot to keep dependencies and action versions up to date.
- Replace the kubeconfig secret with OIDC: GitHub obtains temporary credentials from Azure, AWS or Google Cloud without storing passwords.
- Test against several versions at once with `strategy.matrix` and reuse workflows across repositories.
