Running Ansible from a scheduled CI pipeline instead of cron or AWX
The earlier Ansible posts covered what goes in the play: host tuning, drift checks with check mode and the OS hardening baseline. Each of them ended with “run it on a schedule” and moved on. This post is about where that schedule lives.
I run Ansible as a scheduled CI pipeline, with the inventory grouped by environment (prd, stg, dev). The examples use that layout.
1. Three places to run a playbook
The usual options:
- Cron on a management host. One box with Ansible installed, an SSH key, a crontab and a log file.
- AWX (or its commercial version). A web app that stores inventories, credentials and job templates, and runs playbooks on a schedule or on demand.
- A CI pipeline. The repo that holds the playbooks also defines jobs that run them, on a schedule and on demand.
All three run the same ansible-playbook. What differs is who can start a run, what code it runs, where the credentials live, and where the output goes.
2. Why CI
The code that runs is the code that was reviewed. A pipeline checks out a commit. If changes reach main through review, every run uses reviewed code. On a cron box the checkout drifts too: someone pulls a branch, or edits a file in place at night.
Scheduled and manual runs take the same path. The nightly check and a planned change use the same job, script and Ansible version. If the scheduled job works, the manual one will too.
Every run has a record. CI keeps who started it, which commit, the output and the result. With cron you get a log file on one box, if you remembered to redirect output.
Secrets live in the CI secret store. The SSH key and any vault password are injected into the job and never sit in a home directory. Many CI systems can scope a secret to an environment, so the prd key is only given to the prd job.
No snowflake box. The cron host is one more server to patch and rebuild, and its crontab is often the only copy of the schedule. In CI the schedule is in the repo.
Less to run than AWX. AWX is a real application: it runs on Kubernetes through the AWX Operator, has a database, and needs upgrades and backups. If you already run CI, the pipeline is one more file.
3. What you give up
This isn’t free, and AWX does some things better.
- Access control. AWX has RBAC per inventory, credential and job template. You can let someone run one template against stg and nothing else. In CI, permissions are usually per repo plus whatever environment protection your CI offers. That’s coarser.
- Inventory UI and job history per host. AWX shows which jobs touched a host and what happened. CI shows runs, not hosts. You find a host by searching logs.
- Provisioning callbacks and surveys. AWX lets a new host ask for its own configuration on boot, and gives operators a form for extra variables. In CI you build this yourself, or do without.
- The runner needs reach and credentials. A hosted CI runner usually can’t reach private hosts in a VPC. You need a self-hosted runner inside the network, with SSH access to every host it manages. That makes the runner a high-value machine. Harden it like a bastion and keep it on its own.
- Locking is your problem. Two runs against the same hosts at once is a bad time. CI concurrency controls only cover runs that go through CI.
- Long runs and timeouts. A play with
serial: 1and reboots across a big group can take hours. If the CI job times out halfway, you’re left with some hosts changed and some not.
Cron is fine for one person and a handful of hosts. AWX makes sense when many teams need self-service runs with fine-grained permissions. CI fits in between: a team that already reviews changes in a repo and wants runs to follow the same path.
4. One script for every run
Don’t put Ansible flags in the pipeline file. Put them in a script that the pipeline and people both call:
#!/usr/bin/env bash
# scripts/run-play.sh <env> <check|apply> [extra limit]
set -euo pipefail
env="$1"; mode="$2"; extra="${3:-}"
limit="$env"
if [ -n "$extra" ]; then limit="$env:&$extra"; fi
args=(-i inventory/hosts.yml site.yml --limit "$limit" --diff)
if [ "$mode" = check ]; then
args+=(--check)
else
args+=(-e lowlat_change_window_open=true)
fi
mkdir -p logs
ANSIBLE_LOG_PATH="logs/${env}-${mode}.log" \
.venv/bin/ansible-playbook "${args[@]}"
The --limit always starts with the environment. An extra pattern can only narrow it, because prd:&host-p01 is the intersection of the two. A typo in the extra pattern matches nothing, instead of the whole fleet.
The change-window flag (from the tuning play) is only passed on apply. Check mode doesn’t need it: the drift post lets the window assert pass when ansible_check_mode is true.
5. Pin the toolchain
A scheduled job that installs “latest” will one day run a new Ansible version nobody tested, at 3am, against prd. Pin everything:
# requirements.txt
ansible-core==2.18.1
# requirements.yml
collections:
- name: ansible.posix
version: "1.6.2"
- name: community.general
version: "10.1.0"
# scripts/setup.sh
set -euo pipefail
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
.venv/bin/ansible-galaxy collection install -r requirements.yml -p ./collections
Set collections_path = ./collections in ansible.cfg so the play uses what you installed, not whatever is on the runner. Bump versions in a reviewed change, run the check against dev and stg, then merge. The versions above are just the shape; pin what you’ve tested.
6. The pipeline
The example below is GitHub Actions syntax. Other CI systems have the same pieces under different names: schedules, manual triggers with inputs, environments with approvals, concurrency groups, timeouts and artifacts.
# .github/workflows/ansible.yml
name: ansible
on:
schedule:
- cron: "30 21 * * *" # UTC
workflow_dispatch:
inputs:
mode:
type: choice
options: [check, apply]
default: check
limit:
description: "Optional pattern to narrow each environment"
type: string
default: ""
permissions:
contents: read
jobs:
check:
if: github.event_name == 'schedule' || inputs.mode == 'check'
runs-on: [self-hosted, ansible]
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
env: [dev, stg, prd]
concurrency:
group: ansible-${{ matrix.env }}
cancel-in-progress: false
steps:
- uses: actions/checkout@v4
- run: bash scripts/setup.sh
- run: bash scripts/run-play.sh "${{ matrix.env }}" check "${{ inputs.limit }}"
- uses: actions/upload-artifact@v4
if: always()
with:
name: check-${{ matrix.env }}
path: logs/
retention-days: 30
apply-dev:
if: >-
github.event_name == 'workflow_dispatch'
&& inputs.mode == 'apply'
&& github.ref == 'refs/heads/main'
runs-on: [self-hosted, ansible]
environment: dev
timeout-minutes: 120
concurrency:
group: ansible-dev
cancel-in-progress: false
steps:
- uses: actions/checkout@v4
- run: bash scripts/setup.sh
- run: bash scripts/run-play.sh dev apply "${{ inputs.limit }}"
- uses: actions/upload-artifact@v4
if: always()
with:
name: apply-dev
path: logs/
retention-days: 90
# apply-stg is the same job with needs: apply-dev and environment: stg
apply-prd:
needs: apply-stg
runs-on: [self-hosted, ansible]
environment: prd # required reviewers set on this environment
timeout-minutes: 240
concurrency:
group: ansible-prd
cancel-in-progress: false
steps:
- uses: actions/checkout@v4
- run: bash scripts/in-window.sh
- run: bash scripts/setup.sh
- run: bash scripts/run-play.sh prd apply "${{ inputs.limit }}"
- uses: actions/upload-artifact@v4
if: always()
with:
name: apply-prd
path: logs/
retention-days: 90
How the parts fit:
- The schedule only checks. It runs check mode with
--diffagainst every environment. The drift post covers turning that output into an alert. Nothing scheduled ever applies. - Applies are manual and only from main. The
github.refcondition stops someone from applying a branch that hasn’t been reviewed. - Promotion is built in.
needschains dev, stg and prd. If dev fails, stg and prd don’t start. - prd waits for a person. Required reviewers on the
prdenvironment pause the job until someone approves it, and “prevent self-review” stops people approving their own run. Environment secrets are only given to the job after the protection rules pass, so the prd SSH key is out of reach until then. Environments on private repos aren’t available on every plan, so check yours. - One run per environment at a time. The concurrency group queues a second run instead of starting it. With
cancel-in-progress: falsea running apply is never killed by a newer one. GitHub keeps at most one pending run per group, and a newer pending run replaces the older one. - Logs are artifacts. Keep check logs long enough to see when drift started, and apply logs long enough for a postmortem.
Two things about schedules catch people out. The cron expression is in UTC, so the local time moves when daylight saving starts or ends. And scheduled runs can start late when the service is busy. That’s fine for a drift check, and one more reason not to schedule applies.
The check jobs in this example use the same SSH key as applies. Better is a separate account for checks, as the drift post suggests, stored as a secret on a different environment.
7. Change windows
For trading hosts, the prd window is outside trading hours, and the play’s own assert only knows whether a flag was passed. Add a check in the pipeline that looks at the clock:
#!/usr/bin/env bash
# scripts/in-window.sh: allow prd applies only inside the agreed window
set -euo pipefail
tz="${WINDOW_TZ:-Australia/Sydney}"
day=$(TZ="$tz" date +%u) # 1 = Monday ... 7 = Sunday
hour=$(TZ="$tz" date +%H)
if [ "$day" -eq 6 ] && [ $((10#$hour)) -ge 8 ] && [ $((10#$hour)) -lt 18 ]; then
exit 0
fi
echo "Outside the prd change window ($tz). Not applying." >&2
exit 1
The 10# matters: date +%H returns 08 and 09, which bash arithmetic would otherwise read as invalid octal.
Use the market’s time zone, not the runner’s, and whatever window your team agreed. Keep exceptions (holidays, early closes) next to the script and review them like any other change. The approval says a person looked at it; the window check says it’s a safe time.
8. Batches, limits and long runs
Inside each environment, the play still controls how fast it moves. The tuning play used serial: 1. For bigger groups a list works well:
- name: Baseline
hosts: all
become: true
serial: [1, "10%", "25%"]
max_fail_percentage: 0
One host first, then 10%, then 25% per batch until done. Any failure stops the play, so a bad change stops after one host.
Set the CI timeout longer than the slowest normal run, with margin. If a job does time out, the hosts in the current batch may be half done. That’s survivable only if the play is idempotent: rerun it, and hosts that are already right report ok, the rest get finished. Two runs in a row with zero changes on the second is the test, same as in the tuning post.
For a single host, use the limit input. It narrows the environment; it can’t widen it.
9. Locking outside CI
The concurrency group only stops two CI runs. It doesn’t stop someone running ansible-playbook from a laptop at the same moment. Two ways to deal with it:
- Make CI the only path for applies to stg and prd. The SSH key for those environments only exists in CI. People can still run check mode against dev from their own machine.
- Add a lock in the play if you need belt and braces: a pre-task that creates a lock file on the hosts and fails if one exists, with a post-task that removes it. A failed run leaves the lock behind, so you need a documented way to clear it.
The first is simpler and also answers “who changed this host”.
10. Notifications
CI failure emails tend to go to one person. For scheduled runs that’s often whoever last edited the schedule. Send results to the team channel instead:
- Check found drift (
changed> 0): a normal ticket, not a page. The drift post covers what to do with it. - Check failed or hosts unreachable: the check itself is broken. Treat it like a monitoring gap.
- Apply failed: tell whoever started it, with a link to the run and the log artifact.
- Scheduled run didn’t happen: easy to miss. Some CI systems disable schedules on repos with no recent activity. A dead man’s switch on “last successful check” catches it.
Checklist
- One script runs Ansible; CI and people both call it
- ansible-core and collections pinned, installed into the job
- Schedule runs check mode with
--diffonly; applies are manual from main - Applies promoted dev → stg → prd, prd behind an approval
- prd secrets scoped to the prd environment
- prd apply checks the change window in the market’s time zone
- One run per environment at a time; stg and prd keys only in CI
-
serialbatches withmax_fail_percentage: 0; timeouts set with margin - Logs kept as artifacts; results sent to the team
- An alert if the scheduled check stops running
References
- Ansible: patterns for targeting hosts
- Ansible: controlling playbook execution (serial, max_fail_percentage)
- Ansible: installing collections from a requirements file
- GitHub Actions: workflow syntax
- GitHub Actions: control the concurrency of workflows and jobs
- GitHub Actions: managing environments for deployment
- AWX project