Codex CLI Automation: 3 Workflow Patterns for GitHub Actions, Cron & CI¶
Target Audience
- Intermediate developers with CI/CD experience and basic Codex CLI knowledge
Key Points¶
- Automate Codex CLI execution in GitHub Actions (scheduled runs, PR triggers)
- Set up cron jobs for nightly batch processing with log management
- Integrate Codex into CI/CD pipelines with failure retry logic
Why This Matters Now¶
Codex CLI users seek concrete automation integration patterns beyond design principles. This article complements existing principle guides (codex-cli-best-practices.md) with production-ready workflow implementations.
Solution Steps Overview¶
| Step | Content | Success Criteria |
|---|---|---|
| 1 | GitHub Actions integration (scheduled, PR-triggered) | Workflow executes successfully |
| 2 | Cron job integration (nightly batch, log management) | Crontab entry runs as expected |
| 3 | CI/CD pipeline integration (failure retry) | Build step completes successfully |
Step 1: GitHub Actions Integration Pattern¶
Scheduled Execution (Daily at 6:00 AM JST)¶
name: Codex Daily Automation
on:
schedule:
- cron: '0 21 * * *' # UTC 21:00 = JST 06:00
jobs:
auto-update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Codex CLI
run: |
npm install -g @openai/codex-cli
codex --version
- name: Run Automated Task
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex --full-auto \
--log-file ./codex.log \
"Update dependencies and run tests" || echo "Task failed but continuing"
- name: Commit Changes
run: |
git config user.name "Codex Bot"
git config user.email "bot@example.com"
git add -A
git diff --staged --quiet || git commit -m "🤖 Automated update by Codex CLI"
git push
Key Points: - --full-auto auto-approves all operations (secure CI environment assumed) - || echo "..." allows workflow continuation on error (failures handled in separate step) - git diff --staged --quiet prevents empty commits
PR Trigger (Automated Review)¶
name: Codex PR Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Codex CLI
run: npm install -g @openai/codex-cli
- name: Auto Review PR
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
git diff origin/$GITHUB_BASE_REF...HEAD > diff.txt
codex --approval never --sandbox workspace-write \
"Review this PR diff and suggest improvements: $(cat diff.txt)" \
> review.md
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: review
});
Step 2: Cron Job Integration Pattern¶
Nightly Batch Processing (With Log Management)¶
# crontab -e
0 3 * * * /home/user/scripts/codex-nightly.sh >> /var/log/codex-nightly.log 2>&1
codex-nightly.sh Implementation:
#!/bin/bash
set -euo pipefail
LOG_DIR="/var/log/codex"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="${LOG_DIR}/codex_${TIMESTAMP}.log"
mkdir -p "$LOG_DIR"
echo "$(date): Starting Codex nightly task" | tee -a "$LOG_FILE"
cd /path/to/project || exit 1
# Auto-approval mode with 3 retry attempts
for i in {1..3}; do
if codex --full-auto \
--log-file "$LOG_FILE" \
"Analyze codebase and update documentation"; then
echo "$(date): Success on attempt $i" | tee -a "$LOG_FILE"
break
else
echo "$(date): Attempt $i failed, retrying..." | tee -a "$LOG_FILE"
sleep 30
fi
done
# Delete logs older than 7 days
find "$LOG_DIR" -name "codex_*.log" -mtime +7 -delete
echo "$(date): Task completed" | tee -a "$LOG_FILE"
Failure Notification (Optional):
# Slack notification on failure
if ! codex ...; then
curl -X POST https://hooks.slack.com/services/YOUR/WEBHOOK/URL \
-d '{"text":"Codex nightly task failed"}' || true
fi
Step 3: CI/CD Pipeline Integration Pattern¶
GitLab CI Example (Test Auto-Fix)¶
stages:
- test
- fix
run_tests:
stage: test
script:
- npm test
allow_failure: true
artifacts:
reports:
junit: test-results.xml
auto_fix:
stage: fix
when: on_failure
dependencies:
- run_tests
script:
- npm install -g @openai/codex-cli
- |
codex --approval never --sandbox workspace-write \
"Fix failing tests based on test-results.xml" || exit 0
- git add -A
- git diff --staged --quiet || git commit -m "🤖 Auto-fix by Codex"
- git push origin HEAD:$CI_COMMIT_REF_NAME
Jenkins Pipeline Example (Build Failure Auto-Diagnosis)¶
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm run build'
}
}
stage('Auto-Diagnose on Failure') {
when { expression { currentBuild.result == 'FAILURE' } }
steps {
sh '''
codex --full-auto \
"Analyze build failure logs and suggest fixes: $(cat build.log)" \
> diagnosis.txt
cat diagnosis.txt
'''
}
}
}
}
Common Pitfalls and Solutions¶
| Symptom | Cause | Immediate Fix |
|---|---|---|
| Permission error in GitHub Actions | Insufficient token scope | Add contents: write permission to GITHUB_TOKEN |
| Cron doesn't execute | Missing env variables | Add OPENAI_API_KEY=/path/to/key to crontab or source ~/.bashrc in script |
| Infinite loop in CI/CD | Commits re-trigger workflow | Add [skip ci] to commit messages from workflow |
| Log file bloat | Old logs not deleted | Implement find ... -mtime +7 -delete from script above |
Advanced Configuration
### Granular Approval Policy Control# Auto-approve file writes only (network requires manual approval)
codex --approval never \
--sandbox workspace-write \
--allow-file-write \
"Task description"
# Restrict access outside specific directories
codex --approval never \
--sandbox custom \
--allowed-paths ./src,./tests \
"Task description"
#!/bin/bash
TASKS=(
"Update package dependencies"
"Run security audit and fix"
"Update changelog"
)
for task in "${TASKS[@]}"; do
echo "Executing: $task"
codex --full-auto "$task" || {
echo "Failed: $task"
exit 1
}
done
# Periodic check of OpenAI API usage (requires API key)
codex --approval never "Check current API usage" | \
grep -oP '(?<=tokens: )\d+' > usage.txt
Next Steps¶
- Codex CLI Best Practices — Design principles & change management
- GitHub Actions Integration Guide — Detailed GitHub Actions implementations
- Claude Code Cron Automation Guide — Similar patterns for Claude Code