Files
Sherif Emad d67d814144
lint / lint (push) Failing after 10s
lint / smoke (push) Skipped
init
2026-11-08 15:39:22 +02:00

500 lines
20 KiB
Markdown

# ci-templates
Shared Gitea Actions scripts and reusable actions. Projects reference this repo instead of copy-pasting workflow code.
- **Actions** (`actions/<name>/action.yml`) are composite actions that projects call with `uses:`.
- **Scripts** (`scripts/*.sh`) are bash scripts that the actions run. They live in the same repo and the same tag as the actions.
> Why is this simpler than the GitLab version? `uses: org/repo/path@ref` checks out the whole repo at that ref, so an action can call `${{ github.action_path }}/../../scripts/x.sh` directly. There is no separate clone step, no job token allowlist, and only one version pin.
---
## Table of contents
1. [Repo layout](#1-repo-layout)
2. [Quick start: using the repo from a project](#2-quick-start-using-the-repo-from-a-project)
3. [How it works](#3-how-it-works)
4. [Catalog](#4-catalog)
5. [Standards](#5-standards)
6. [Adding a new script](#6-adding-a-new-script)
7. [Adding a new action](#7-adding-a-new-action)
8. [Testing changes](#8-testing-changes)
9. [Versioning and releases](#9-versioning-and-releases)
10. [One-time setup](#10-one-time-setup)
11. [Troubleshooting](#11-troubleshooting)
12. [Contribution checklist](#12-contribution-checklist)
---
## 1. Repo layout
```
ci-templates/
├── .gitea/workflows/
│ └── lint.yml # lints this repo (shellcheck + yamllint) and smoke-tests the actions
├── README.md # this file
├── CHANGELOG.md # one entry per release
├── scripts/
│ ├── hello.sh
│ ├── notify.sh
│ └── auto-tag.sh
├── actions/
│ ├── hello/action.yml # calls scripts/hello.sh
│ ├── notify/action.yml # calls scripts/notify.sh
│ └── auto-tag/action.yml # calls scripts/auto-tag.sh
└── consumer-example/
└── .gitea/workflows/ci.yml # sample workflow for a consuming project
```
---
## 2. Quick start: using the repo from a project
Add this to the consuming project's `.gitea/workflows/ci.yml`. Replace `gitea.example.com` and `devops/ci-templates` with the real host and path of this repo.
```yaml
name: ci
on:
push:
branches: [main]
jobs:
say-hello:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.example.com/devops/ci-templates/actions/hello@v1.0.0 # always pin a tag, avoid main
with:
name: Sherif
```
Short form: if the instance sets `DEFAULT_ACTIONS_URL = self` in `app.ini` (`[actions]` section), you can write `uses: devops/ci-templates/actions/hello@v1.0.0` instead of the full URL. Without it, short names resolve to github.com.
Rules for consumers:
- Always pin a tag in `uses: ...@vX.Y.Z`. That one pin controls both the action YAML and the scripts.
- Configure actions through `with:` inputs. The defaults are documented in each `action.yml` header comment.
- Actions never set `runs-on`, triggers or conditions. The consumer's workflow decides when and where a job runs.
- The runner image must have `bash` (and `git` for `auto-tag`).
---
## 3. How it works
```
consumer workflow
│
└─ job step: uses: <host>/devops/ci-templates/actions/hello@v1.0.0
│
├─ runner fetches the repo at ref v1.0.0
├─ reads actions/hello/action.yml (composite action)
└─ step runs:
${{ github.action_path }}/../../scripts/hello.sh "$GREET_NAME"
```
`github.action_path` points to the checked-out `actions/hello` directory, so `../../scripts/` is the scripts folder of the same tag. Actions and scripts can never be out of sync.
Results are returned to the caller through action **outputs** (for example `steps.tag.outputs.tag`). To pass them to later jobs, expose them as job `outputs:` and read them with `needs.<job>.outputs.<name>`.
---
## 4. Catalog
Keep this section current. Update it in the same pull request that adds or changes a script or action.
### Actions
| Path | Purpose | Needs |
|---|---|---|
| `actions/hello` | Prints a greeting and CI info (example) | bash |
| `actions/notify` | Prints a notification line (stub for a webhook) | bash |
| `actions/auto-tag` | Calculates (and optionally pushes) the next git tag | bash, git, checkout with `fetch-depth: 0` |
| `actions/check-tags` |
### Scripts
| Script | Purpose | Inputs |
|---|---|---|
| `scripts/hello.sh` | Prints a greeting and CI info | arg 1: name (default `world`) |
| `scripts/notify.sh` | Prints a notification line (stub for a webhook) | arg 1: status, arg 2: message |
| `scripts/auto-tag.sh` | Calculates the next tag, writes `tag.env`, optionally pushes | env: `TAG_TYPE`, `TAG_ENV`, `PUSH_TAG`, `GIT_PUSH_TOKEN` |
### Action inputs
| Action | Input | Default | Meaning |
|---|---|---|---|
| `hello` | `name` | `world` | Name to greet |
| `notify` | `status` | `info` | Status word in the message |
| `notify` | `message` | `pipeline step finished` | Message text |
| `auto-tag` | `tag-type` | none, **required** | Tag prefix: `dev`, `beta`, `prod`, ... |
| `auto-tag` | `tag-env` | empty | `production` switches to the `<type>-<max>.<major>.<minor>` scheme |
| `auto-tag` | `push-tag` | `"false"` | `"true"` creates and pushes the tag |
| `auto-tag` | `push-token` | empty | Token with write access to the consuming repo. Required only when `push-tag` is `"true"`. Pass a secret. |
### Action outputs
| Action | Output | Meaning |
|---|---|---|
| `auto-tag` | `tag` | The new tag |
| `auto-tag` | `previous-tag` | Latest existing tag with this prefix (empty if none) |
| `auto-tag` | `stream` | The tag type (prefix) |
### Auto-tag behavior
This ports the Jenkins AutoTag stage. It tags the **consuming** repo, unrelated to the releases of this repo.
| Mode | Latest tag | New tag | Starting point |
|---|---|---|---|
| non-production (`tag-env` not `production`) | `dev-5` | `dev-6` | `dev-0` → `dev-1` |
| `tag-env: production` | `prod-1.2.3` | `prod-2.2.3` | `prod-1.0.0` → `prod-2.0.0` |
In production mode only the first number is bumped and major/minor are carried over. The first production tag is therefore `-2.0.0`, not `-1.0.0`. This matches the original Groovy logic.
The script also writes `tag.env` (`TAG`, `STREAM`, `PREVIOUS_TAG`) in the working directory for local use.
---
## 5. Standards
### 5.1 Naming
- Files and directories: `kebab-case`. Scripts end in `.sh`; every action is a directory containing `action.yml`.
- Action names use the topic: `auto-tag`, `deploy-k8s`.
- Action inputs and outputs: `kebab-case` (`tag-type`, `previous-tag`).
- Script environment variables: `UPPER_SNAKE_CASE`, with a shared prefix when several belong together.
- One concern per action. Prefer several small actions over one large one.
### 5.2 Scripts
Every script must:
- Start with `#!/usr/bin/env bash` and `set -euo pipefail`.
- Begin with a header comment: purpose, usage line, inputs (args and env vars), outputs.
- Validate required inputs early with a clear message: `X="${X:?X is required}"`.
- Read configuration from environment variables or arguments. Never hardcode hosts, repo paths, or credentials.
- Print errors to stderr and exit non-zero on failure. Print a short log of what it is doing.
- Never echo secrets. Do not enable `set -x` in scripts that handle tokens.
- Pass `shellcheck` with no warnings.
- Be executable and committed as such (`chmod +x`, see section 6).
- Prefer `sed -n 1p` over `head -n 1` after a pipe in scripts using `pipefail` (avoids SIGPIPE failures).
- Write results to `$GITHUB_OUTPUT` (when set) so actions can expose them as outputs.
### 5.3 Actions
Every action must:
- Be a **composite action** (`runs: using: composite`) in `actions/<name>/action.yml`.
- Start with a header comment: purpose, runner requirements, and every input and output (required or optional, with defaults).
- Declare every input with a `description`, and a `default` for optional ones. Required inputs have `required: true` and the script fails loudly if missing.
- Pass inputs to scripts through `env:`, never by interpolating `${{ inputs.x }}` directly into `run:` (prevents shell injection).
- Call scripts through `${{ github.action_path }}/../../scripts/<name>.sh`.
- Set `shell: bash` on every `run` step (required in composite actions).
- Not set `runs-on`, triggers, `if:` or `continue-on-error`. The consumer decides when and where a job runs.
- Pin any image or action it uses (`actions/checkout@v4`, not `@main`).
- Not install heavy tooling at runtime. Document what the runner needs instead.
- Expose results through `outputs:` mapped from a step `id`.
### 5.4 Compatibility rules (what you may change without breaking consumers)
| Change | Allowed in |
|---|---|
| Fix a bug, no interface change | patch |
| Add a new script or action | minor |
| Add a new **optional** input with a safe default | minor |
| Add a new output | minor |
| Rename or remove an action, input, output, script, or file | **major** |
| Change a default value so behavior differs | **major** |
| Change script arguments or output format | **major** |
| Make an optional input required | **major** |
When in doubt, treat it as breaking.
### 5.5 Commits and pull requests
- Never push directly to `main`. Use a branch and a pull request.
- Commit messages: short imperative summary, optionally prefixed (`feat:`, `fix:`, `docs:`, `chore:`). Breaking changes are marked `feat!:` or `fix!:` and explained in the body.
- Every PR updates the [catalog](#4-catalog) and, for user-visible changes, `CHANGELOG.md`.
- The repo workflow (shellcheck + yamllint + smoke test) must be green before merging.
---
## 6. Adding a new script
1. Create the file under `scripts/`:
```bash
#!/usr/bin/env bash
# <one-line purpose>
# Usage: my-script.sh <arg>
# Inputs (env vars): FOO (required), BAR (optional, default x)
# Outputs: <stdout / files / exit codes>
set -euo pipefail
ARG="${1:?usage: my-script.sh <arg>}"
FOO="${FOO:?FOO is required}"
BAR="${BAR:-x}"
echo "doing the thing with ${ARG}"
```
2. Make it executable, and make sure git records that:
```bash
chmod +x scripts/my-script.sh
git add scripts/my-script.sh
git update-index --chmod=+x scripts/my-script.sh
```
3. Lint and run it locally:
```bash
shellcheck scripts/my-script.sh
FOO=1 ./scripts/my-script.sh test
```
4. Expose it through an action (see next section) so projects can use it.
5. Add it to the [catalog](#4-catalog).
---
## 7. Adding a new action
1. Create `actions/<topic>/action.yml`:
```yaml
# Action: <name>. <one-line purpose>
#
# Inputs consumers set:
# foo required what it is
# bar optional default "x"
#
# Outputs: <e.g. result>
#
# Needs: bash on the runner.
name: my-action
description: <one line>
inputs:
foo:
description: what it is
required: true
bar:
description: what it is
required: false
default: x
outputs:
result:
description: what it is
value: ${{ steps.run.outputs.RESULT }}
runs:
using: composite
steps:
- name: Run my-script.sh
id: run
shell: bash
env:
FOO: ${{ inputs.foo }}
BAR: ${{ inputs.bar }}
run: '"${{ github.action_path }}/../../scripts/my-script.sh" "$FOO"'
```
2. Validate it:
```bash
python3 -c "import yaml; yaml.safe_load(open('actions/<topic>/action.yml')); print('ok')"
yamllint -d relaxed actions/
```
3. Add a usage example to `consumer-example/.gitea/workflows/ci.yml`.
4. Add a step to the `smoke` job in `.gitea/workflows/lint.yml` that calls it with `uses: ./actions/<topic>`.
5. Add it to the [catalog](#4-catalog) and to `CHANGELOG.md`.
6. Test it from a real consumer repo on a branch (next section).
---
## 8. Testing changes
### Level 1: local, no Gitea needed
```bash
bash -n scripts/*.sh # syntax check
shellcheck scripts/*.sh # lint
```
For scripts that use git (like `auto-tag.sh`), test against a throwaway repo:
```bash
mkdir /tmp/tagtest && cd /tmp/tagtest
git init -q . && git commit -q --allow-empty -m init
git tag dev-1 && git tag dev-9 && git tag dev-10
TAG_TYPE=dev /path/to/ci-templates/scripts/auto-tag.sh # expect dev-11
TAG_TYPE=prod TAG_ENV=production /path/to/ci-templates/scripts/auto-tag.sh # expect prod-2.0.0
```
### Level 2: this repo's own workflow
`.gitea/workflows/lint.yml` runs shellcheck and yamllint, then smoke-tests every action with `uses: ./actions/<name>`. Keep it green.
### Level 3: real consumer workflow, on a branch
1. Push your changes to a branch, e.g. `feat/new-action`.
2. In a test repo, point the pin at the branch:
```yaml
jobs:
my-test:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.example.com/devops/ci-templates/actions/my-topic@feat/new-action
with:
foo: bar
```
3. Run the workflow and read the job log.
4. Merge, release a tag, then switch consumers to the tag.
---
## 9. Versioning and releases
This repo uses **semantic versioning** with git tags: `vMAJOR.MINOR.PATCH`. Consumers pin a tag, so a change on `main` can never break a workflow until someone upgrades on purpose.
### 9.1 Choosing the next version
Use the table in [section 5.4](#54-compatibility-rules-what-you-may-change-without-breaking-consumers).
| Example change | Bump |
|---|---|
| Fix a typo in an error message | `v1.0.0` → `v1.0.1` |
| Add `actions/deploy-k8s` | `v1.0.1` → `v1.1.0` |
| Rename `actions/hello` to `actions/greet` | `v1.1.0` → `v2.0.0` |
### 9.2 Release steps
```bash
# 1. be on an up-to-date main, with the PR merged and the workflow green
git checkout main && git pull
# 2. update CHANGELOG.md (see format below) and commit it
git add CHANGELOG.md
git commit -m "docs: changelog for v1.1.0"
git push origin main
# 3. create an annotated tag and push it
git tag -a v1.1.0 -m "v1.1.0: add auto-tag action"
git push origin v1.1.0
```
Optionally also maintain a **moving major tag** (`v1`) so consumers who accept non-breaking updates can follow it:
```bash
git tag -fa v1 -m "v1 -> v1.1.0"
git push --force origin v1
```
Runners may cache a fetched action by ref, so a moving tag can lag on busy runners. Pinning the full version is the reliable choice.
If the push is rejected (for example by protected-tag rules), delete the remote tag and push it again. Never move a full-version tag like `v1.1.0` once published. To fix a bad release, publish `v1.1.1`.
Consider protecting `v*` tags (Repository Settings → Tags → Protected tags) so only maintainers can create them. Optionally also create a Gitea Release from the tag with the changelog text.
### 9.3 Changelog format
Newest first, one section per release:
```markdown
# Changelog
## v1.1.0 - 2026-11-15
### Added
- `actions/deploy-k8s` and `scripts/deploy-k8s.sh`
### Changed
- ...
### Fixed
- ...
### Breaking
- (none)
```
### 9.4 Upgrading a consumer
Change the **one** pin in the consuming repo, then run its workflow:
```yaml
- uses: https://gitea.example.com/devops/ci-templates/actions/hello@v1.1.0 # <- here
```
For a major upgrade, read the `Breaking` section of the changelog first.
### 9.5 Deprecation
Do not delete an action or input abruptly. Keep the old name working for at least one minor release, print a `WARNING: X is deprecated, use Y` line from the step, note it in the changelog, and remove it in the next major.
### 9.6 Auto-tag vs releases of this repo
`auto-tag` generates tags such as `dev-12` or `prod-3.0.1` for **other** repos. This repo's own releases are always manual `vX.Y.Z` tags. Do not mix the two schemes.
---
## 10. One-time setup
1. **Create the repo** in Gitea as `devops/ci-templates`. Visibility `public` (simplest) or `internal`/`private` with the access notes below.
2. **Enable Actions** on the instance (`[actions] ENABLED = true`) and have at least one `act_runner` registered with the label your workflows use (`ubuntu-latest` in these examples). The runner image needs `bash` and `git`, and Node.js for `actions/checkout`.
3. **Let consumers resolve the actions.**
- Either use the full URL in `uses:` (as in the examples), or set `DEFAULT_ACTIONS_URL = self` in `app.ini` to allow the short form.
- For a `private` repo, the workflow token must be able to read it. Safest options: make this repo `internal`/`public` within your org, or keep consumers in the same org.
- `actions/checkout@v4` itself resolves from github.com by default. If the runner has no internet, mirror it into Gitea and use its full URL.
4. **Tag auto-pushing (only if you use `push-tag: "true"`).** In the consuming repo:
- Create an access token with write access to repository contents (a dedicated bot user with Write role is best).
- Save it as a repository or org **secret** named `GIT_PUSH_TOKEN` and pass it as `push-token: ${{ secrets.GIT_PUSH_TOKEN }}`.
5. **Protect `main`** and require pull requests and a green check.
6. Optionally protect `v*` tags.
---
## 11. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Step fails resolving `uses:` (clone error, 404, "repository not found") | Wrong host/path in the URL, short form used without `DEFAULT_ACTIONS_URL = self`, or runner cannot read the repo | Use the full URL, check the path, make the repo readable by the runner |
| Runner tries github.com for `devops/ci-templates/...` | Short form without `DEFAULT_ACTIONS_URL = self` | Use the full URL or set the option |
| `hello.sh: No such file or directory` | Action called from a copy that does not include `scripts/`, or `github.action_path` unsupported on an old runner | Reference the action by `uses:` from the repo (not copied files); update `act_runner` |
| `Permission denied` running a script | Executable bit not committed | `git update-index --chmod=+x scripts/<file>`, commit |
| `bash: not found` / `git: not found` | Slim runner image without them | Use a runner image that includes them |
| `Required property is missing: shell` | A composite `run` step without `shell:` | Add `shell: bash` |
| auto-tag always returns the first tag | Shallow clone, tags missing | Checkout with `fetch-depth: 0` |
| `latest tag '...' is not in the expected format` | A tag with the same prefix but a different format exists (e.g. `dev-abc`) | Delete or rename the odd tag, or use a different `tag-type` |
| `steps.tag.outputs.tag` empty | Wrong step `id`, or action failed before writing outputs | Check the id and the step log |
| Tag output empty in a later job | Job output not declared | Add `outputs:` to the job and use `needs.<job>.outputs.tag` |
| New behavior not showing after release | Runner cached the old ref (usually with moving tags like `v1`) | Pin the full tag, or clear the runner cache |
| `push-tag: "true"` fails on push | Token missing, no write access, or tag protection blocks it | Check the secret, the bot's role, and protected tag rules |
| `fatal:` couldn't find remote ref <branch> in check-tags | The branch input does not exist on origin, or the workflow ran on a tag ref | Pass branch: explicitly |
| `TAGS_VERSION` must be one of major|minor|test|cib | Wrong tags-version value | Use one of the four values |
---
## 12. Contribution checklist
Copy into every pull request:
```markdown
- [ ] Script has shebang, `set -euo pipefail`, header comment, input validation
- [ ] `shellcheck` clean; script executable and committed as such
- [ ] Action is composite, passes inputs via `env:`, sets `shell: bash` on every run step
- [ ] Action header documents requirements, inputs, outputs with defaults
- [ ] No `runs-on`/triggers/`if:` inside actions; third-party actions pinned
- [ ] Smoke step added to `.gitea/workflows/lint.yml`
- [ ] Tested locally and from a consumer repo on a branch
- [ ] Catalog in README updated
- [ ] CHANGELOG.md updated; version bump chosen per section 5.4
- [ ] Breaking change? Marked in the commit, changelog, and bumped as major
```
---
## Future option: reusable workflows
Gitea also supports `workflow_call` reusable workflows (check your Gitea version). They suit whole pipelines (build, test, deploy) while composite actions suit single steps. If this repo grows, add them under `.gitea/workflows/` and keep the same versioning rules above.