# Codex exec: running Codex automatically in scripts and CI

URL: https://opcaios.org/en/blog/codex-exec-chay-tu-dong
Date: 2026-11-03
Author: Lê Quốc Nghĩa

# What is Codex exec?

Codex exec is the non-interactive mode of the Codex CLI: the `codex exec` command takes a request, lets OpenAI's Codex agent work in the project directory, prints progress to standard error (stderr) and only prints the final answer to standard output (stdout), then exits, so it can be called from scripts, cron, or CI processes like GitHub Actions. This post does not promise that codex exec "does it safely for you": unattended runs can fail, waste tokens, or overshoot, so the machine only drafts and the person reviews before merging or publishing. To be clear: OPCAIOS has not yet run codex exec in CI; the content is based on the "Non-interactive mode" and "GitHub Action" pages of the Codex documentation plus `codex exec --help` version 0.162.1, read on 03/11/2026. The corresponding part for [Claude Code](/tien-ich/claude-code) is in the post [run Claude Code automatically every day](/blog/chay-claude-code-tu-dong-moi-ngay).

![Diagram of codex exec running automatically: schedule or pull request event triggers codex exec with read-only sandbox or workspace-write, API key is a secret granted only to the step that needs it, JSON output or result file according to schema, separate job has permission to write comments or open a pull request, person reviews then merges](https://opcaios.org/images/blog/codex-exec-chay-tu-dong/so-do.webp)
*Trigger, run with narrow permissions, export results, person reviews at the end. Diagram: OPCAIOS.*

## How does the codex exec command run and what is it allowed to do by default?

The `codex exec` command runs Codex without opening an interactive terminal UI (TUI), and by default is only allowed to read. According to the "Non-interactive mode" page on learn.chatgpt.com/docs (developers.openai.com/codex redirects there, read on 03/11/2026), the default sandbox for `codex exec` is read-only; to allow file edits you must choose `--sandbox workspace-write`. The documentation notes that the `--full-auto` flag is no longer supported, replaced by `--sandbox workspace-write`. The command requires running in a Git repository; only skip it with `--skip-git-repo-check` when the environment is safe. According to `codex exec --help` version 0.162.1, if you don't pass a request (or pass `-`) the command reads from standard input. The documentation doesn't say anything about exit codes; don't assume anything until you test it yourself.

```bash
codex exec "summarize the repository structure"
```

## Which codex exec flags are important when running in a script?

The important flags of `codex exec` divide into 3 groups, all present in `codex exec --help` version 0.162.1 and documented:

| Group | Flag | Purpose |
|---|---|---|
| Output | `--json` | stdout becomes a JSON Lines stream, one event per line |
| Output | `--output-schema <FILE>` | force the final answer to match a JSON Schema |
| Output | `-o`, `--output-last-message <FILE>` | write the final answer to a file (still print to stdout) |
| Permission | `-s`, `--sandbox` | `read-only`, `workspace-write`, or `danger-full-access` |
| Permission | `--approve-for-me` | switch approval to a self-review mechanism, use with workspace-write sandbox |
| Replay | `--ephemeral` | don't save session files to disk |
| Replay | `--ignore-user-config`, `--ignore-rules` | ignore user's config.toml and `.rules` files |

There is also the `--dangerously-bypass-approvals-and-sandbox` flag, which the help text itself describes as extremely dangerous, meant only for environments already isolated from the outside. The meaning of each sandbox mode is explained in detail in the post [Codex approval and sandbox modes](/blog/che-do-phe-duyet-va-sandbox-cua-codex); config key reference in [Codex config.toml](/blog/cau-hinh-codex-config-toml).

## How do I use JSON output and schema from codex exec?

The JSON output from `codex exec` is an event stream so scripts can track each step, while schema is a way to force the final answer into fixed-form data. According to the documentation (read on 03/11/2026), when you enable `--json`, event types include `thread.started`, `turn.started`, `turn.completed`, `turn.failed`, the `item.*` group (agent messages, reasoning, executed commands, changed files, MCP tool calls, web searches, plan updates), and `error`. With `--output-schema`, you provide a JSON Schema file; for example the documentation sets `"additionalProperties": false`, and combines it with `-o` to save the result as a JSON file that the next step can read. Always verify the result file exists and matches the schema before using it, since a run can fail partway through.

```bash
codex exec --json "summarize the repo structure" | jq
codex exec "Extract project metadata" \
  --output-schema ./schema.json \
  -o ./project-metadata.json

## How to Continue a Codex Exec Session?

Continuing a session lets you reuse all the context from the previous run for the next one, using the `codex exec resume` subcommand. According to the documentation and `codex exec resume --help` in version 0.162.1, there are 2 ways: `--last` to grab the most recent session, or pass the session code (UUID) or session name. For example in the documentation: the first time you find a race condition, the next time you continue the session to fix it. This split works well with a process involving people: the first step is read-only, the person reviews it, and only then does the second step write. Note: sessions run with `--ephemeral` are not saved to disk, so they cannot be continued. The `review` subcommand runs code review; see [using Codex review code](/blog/dung-codex-review-code).

```bash
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"
```

## What is Codex's Official GitHub Action?

Codex's official GitHub Action is `openai/codex-action`, used in the form `uses: openai/codex-action@v1`, which installs the Codex CLI and runs `codex exec` in the GitHub Actions workflow. According to the "GitHub Action" page of the Codex documentation (read on 03/11/2026), the main inputs include:

1. **`openai-api-key`**: OpenAI key from a secret; the action builds a proxy that keeps the key, so the documentation prioritizes this way over passing the key into a shell step yourself.
2. **`prompt` or `prompt-file`**: write the request inline or provide a file path in the repo; use only one of the two.
3. **`sandbox`**: `workspace-write`, `read-only` or `danger-full-access`.
4. **`safety-strategy`**: defaults to `drop-sudo` (strips sudo before Codex runs), also `unprivileged-user` and `unsafe`; Windows requires `unsafe`.
5. **`allow-users`, `allow-bots`**: who can trigger it; defaults to only people with write access to the repo.
6. **`output-file`, `codex-args`, `model`, `codex-version`**: save results, add flags, pick model, pin CLI version.

The `final-message` output contains the final answer. A simplified example from the documentation, with the Codex job having read-only access:

```yaml
jobs:
  codex:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    outputs:
      final_message: ${{ steps.run_codex.outputs.final-message }}
    steps:
      - uses: actions/checkout@v5
        with:
          persist-credentials: false
      - id: run_codex
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt-file: .github/codex/prompts/review.md
          output-file: codex-output.md
```

In the full example, a second job needs `pull-requests: write` permission to post the results as a comment.

## How to Authenticate Codex Safely in CI?

Authenticating Codex safely in CI means the API key lives in a secret and is only given to the commands that need it. According to the "Non-interactive mode" page (read on 03/11/2026), `codex exec` by default reuses saved login info from the CLI; in CI, set the `CODEX_API_KEY` variable on the command line of the call that needs the key. The documentation warns against setting `OPENAI_API_KEY` or `CODEX_API_KEY` at the job level in workflows that run code controlled by the repo. Using ChatGPT login in CI is an advanced option for trusted runners; the documentation recommends against it for public repos or open source, since the `auth.json` file in the Codex directory holds the access token. Three rules to take away:

1. Keys only go in GitHub Secrets, not in workflow files or prompts.
2. Give the key only to the step that runs Codex, not to steps that install libraries or run tests.
3. If a key is compromised, revoke it and create a new one immediately.

```bash
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"
```

See also [security when using AI to write code](/blog/bao-mat-khi-dung-ai-viet-code).

## How to Limit Permissions and Have Someone Review?

Limiting permissions means giving automatic runs the exact minimum permissions they need, and having someone review means a final gate before merge or publish. The Codex documentation (read on 03/11/2026) recommends keeping the Codex job at `contents: read`, publishing patches as artifacts, then using a separate job with write access; only use `danger-full-access` in isolated environments; restrict who can trigger it; sanitize untrusted input to prevent prompt injection. The GitHub Action page also notes that `read-only` blocks file edits and network but Codex still runs with high privileges, so don't rely on it to protect secrets. A practical approach:

1. Automatic runs only create branches, pull requests, or comments; enable branch protection rules.
2. Content (articles, emails) only goes to draft status.
3. The reviewer reads the actual diff, not just an AI summary.
4. Hard-to-reverse actions (delete, send, publish, charge) are not in the automatic run's permissions.

## Example daily codex exec workflow

A hypothetical workflow, not a real person: a course seller wants a summary of new bug reports each morning and a draft for minor fixes.

1. At 6 AM, a `schedule` workflow calls `openai/codex-action@v1` with `sandbox: read-only`, reads the list of new issues exported to a file and writes a classification based on a JSON Schema.
2. The result is saved using `output-file`, and a subsequent job posts a summary comment in the tracking issue.
3. The owner reads it, picks a small bug, and labels it for fixing.
4. Another workflow runs with `workspace-write`, fixes it on a new branch; the job has separate write permissions to open a pull request.
5. The owner runs `/review` or reads the diff, tests pass, then merges.

If a run fails, it's usually just missing a summary. Each run consumes tokens and GitHub run minutes; check OpenAI's official pricing page before scheduling frequently.

## OPCAIOS experience

OPCAIOS has not run codex exec in CI or GitHub Actions, and has not used Codex on the cloud to open pull requests; the flags and workflow files in this post have not been tested on our own repository. Codex CLI version 0.162.x and the Codex desktop app are only used in interactive sessions, alongside Claude Code and [Google Antigravity](/tien-ich/google-antigravity). The daily work on the website (choosing topics and writing SEO posts, writing GitHub repo introductions) calls AI via API and only creates drafts waiting for review, not via Codex. When reviewing those drafts, we have had to fix spelling errors, truncated fields and inflated ratings; the principle "machine drafts, human reviews" is what we actually apply, just not yet to codex exec.

## Frequently asked questions

### How is codex exec different from running codex normally?

Running `codex` normally opens an interactive terminal interface for you to chat and approve each step. `codex exec` takes a request, finishes it, then exits: the process prints to stderr, the final answer prints to stdout, so scripts and CI can read it. According to the documentation read on 03/11/2026, the default sandbox for `codex exec` is read-only, so to allow file editing you must explicitly choose `--sandbox workspace-write`.

### Is the --full-auto flag still supported?

According to the "Non-interactive mode" page of the Codex documentation (read on 03/11/2026), `--full-auto` is no longer supported and should be replaced with `--sandbox workspace-write`. The `codex exec --help` section of version 0.162.1 also does not list this flag. If copying old scripts from the web, check each flag against `--help` of your installed version before putting it in CI.

### Should I use CODEX_API_KEY or log into ChatGPT in CI?

The Codex documentation recommends setting `CODEX_API_KEY` for the right `codex exec` call that needs a key, while the GitHub Action uses the `openai-api-key` input from a secret. Logging into ChatGPT in CI is described as an advanced option for trusted runners and should not be used with public repositories. For solo work, a separate API key for CI with spending limits is easier to revoke and keeps it separate from your personal account.

### Should I let codex exec auto-merge to the main branch?

No. Automated runs should stop at a comment, new branch, or pull request. The Codex documentation recommends keeping jobs running Codex at read permissions, passing patches to another job with write permissions, and limiting who can trigger the workflow. Auto-merge risks turning one error or injected command in an issue straight into production.

### Can someone who doesn't know code automate Codex?

Yes, at a simple level, if starting with read-only tasks like summarizing issues or daily commits with read-only sandbox, and always keeping results as drafts. The hard part is secrets, workflow permissions, and branch protection. Read more about [a safe workflow for using programming agents](/blog/tac-tu-lap-trinh-cho-nguoi-khong-biet-code-quy-trinh-an-toan). For step-by-step guidance, see OPCAIOS's [AI application training course](/services/dao-tao-ung-dung-ai).

*Source: Codex documentation from OpenAI, the "Non-interactive mode" and "GitHub Action" pages at learn.chatgpt.com/docs (developers.openai.com/codex redirects there), plus `codex exec --help` and `codex exec resume --help` from Codex CLI version 0.162.1, read on 03/11/2026; the daily workflow is hypothetical; exit code meaning for codex exec, API pricing, and the commands and workflows in this post have not been verified. Experience is from OPCAIOS.*
