Sub topic 11
Automating with the Metadata API and CI
Earlier chapters ran a validation and a quick deploy by hand. This chapter moves both steps into a script and a CI pipeline. It assumes you can already run sf project deploy validate and sf project deploy quick against a production org. It also assumes you know the quick deploy eligibility rules: tests ran and passed, coverage was met, and the validation is no more than 10 days old.
What the CLI calls under the hood
The Salesforce CLI is a client for the Metadata API. Each CLI command maps to a Metadata API operation, so any tool that can call the API can follow the same pattern.
| CLI command | Metadata API operation | Purpose |
|---|---|---|
| `sf project deploy validate` | `deploy()` with `checkOnly` set to true | Runs a validation and saves nothing |
| `sf project deploy report` | `checkDeployStatus()` | Reads the status of a deployment by ID |
| `sf project deploy quick` | `deployRecentValidation()` | Promotes a recent successful validation |
| `sf project deploy cancel` | `cancelDeploy()` | Stops a deployment that is still running |
Two points follow from this table.
- Validation and a real deployment use the same operation. The difference is the
checkOnlyoption. If you build your own tooling, keep that flag under tight control, because the wrong value turns a harmless check into a production change. - Quick deploy takes only the validation ID. It carries no manifest and no test options. The package contents and the test results are fixed when the validation runs.
The deployRecentValidation() call returns a new deployment ID. Track that ID, not the validation ID, to follow the quick deploy.
Designing the pipeline
A release pipeline has two phases, separated by time and by a human decision.
- Validate. This runs on demand, or on a schedule, in the days before the release. It runs the full test suite against production. The output that matters is the job ID.
- Quick deploy. This runs inside the release window. It takes the job ID from phase 1, requires an approval, and finishes in minutes because no Apex tests run.
Separate the phases into two workflows. If you put them in one, the pipeline cannot wait days for a release window without holding a runner or hitting a timeout.
Authenticating without a browser
CI runners cannot open a browser, so use a non-interactive login. The common options are:
- JWT bearer flow with
sf org login jwt. You need a connected app with a certificate, and a private key stored as a CI secret. This is the usual choice for production. - SFDX auth URL with
sf org login sfdx-url. You export a URL for an already-authorized org and store it as a secret. It is simple to set up, but the URL contains a refresh token, so treat it like a password.
Give the integration user only the permissions it needs. For validation and quick deploy it needs the Modify Metadata or Modify All Data permission in the org, and it needs API access.
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username "$SF_USERNAME" \
--instance-url https://login.salesforce.com \
--alias prodFor a sandbox, use https://test.salesforce.com as the instance URL.
Scripting the validation
Use --json whenever a script reads the output. Human-readable output changes between CLI versions, and the JSON structure is more stable.
The script below runs a validation, saves the full JSON result, and extracts the job ID.
#!/usr/bin/env bash
set -uo pipefail
TARGET_ORG="${1:-prod}"
sf project deploy validate \
--manifest manifest/package.xml \
--test-level RunLocalTests \
--target-org "$TARGET_ORG" \
--wait 120 \
--json > validate.json
status=$?
jq -r '.result.id // empty' validate.json > job-id.txt
if [ "$status" -ne 0 ]; then
echo "Validation failed. Job ID: $(cat job-id.txt)" >&2
jq -r '.result.details.componentFailures[]? | "\(.componentType) \(.fullName): \(.problem)"' validate.json >&2
jq -r '.result.details.runTestResult.failures[]? | "\(.name).\(.methodName): \(.message)"' validate.json >&2
exit "$status"
fi
echo "Validation passed. Job ID: $(cat job-id.txt)"Several details in this script matter.
set -eis left off on purpose. With-e, the script would exit on the failed command before it could print the failures. The script captures$?and handles the failure itself.--wait 120makes the command block for up to 120 minutes. If the wait expires, the deployment keeps running in the org, and you can still read it withsf project deploy report --job-id..result.id // emptyavoids writing the textnullinto the job ID file when authentication fails and no deployment was created.- The job ID file is written even on failure. A failed validation still has a job ID, which you can use with
sf project deploy report.
If your pipeline needs to do other work during a long test run, use --async. The command then returns right after the deployment is queued, and you poll with sf project deploy report --job-id "$(cat job-id.txt)" --json. Polling in a loop with a sleep is easier to control than a single long blocking call.
A validation workflow in GitHub Actions
This workflow runs on demand and uploads the job ID as an artifact. The same structure applies to GitLab CI, Jenkins, Azure DevOps, or any other system that can store files between jobs.
name: validate-release
on:
workflow_dispatch:
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize production
env:
SF_CLIENT_ID: ${{ secrets.SF_CLIENT_ID }}
SF_USERNAME: ${{ secrets.SF_USERNAME }}
SF_JWT_KEY: ${{ secrets.SF_JWT_KEY }}
run: |
printf '%s' "$SF_JWT_KEY" > server.key
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username "$SF_USERNAME" \
--instance-url https://login.salesforce.com \
--alias prod
rm -f server.key
- name: Validate deployment
run: bash scripts/validate.sh prod
- name: Save validation result
if: always()
uses: actions/upload-artifact@v4
with:
name: validation-result
path: |
validate.json
job-id.txtThe if: always() condition keeps the artifact upload running when validation fails, so you can download validate.json and read the failures.
A quick deploy workflow with an approval gate
The second workflow takes the job ID as an input. Attach a GitHub environment named production with required reviewers, and the job pauses until someone approves it.
name: quick-deploy-release
on:
workflow_dispatch:
inputs:
job_id:
description: "Validated deployment ID (starts with 0Af)"
required: true
jobs:
quick-deploy:
runs-on: ubuntu-latest
environment: production
steps:
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize production
env:
SF_CLIENT_ID: ${{ secrets.SF_CLIENT_ID }}
SF_USERNAME: ${{ secrets.SF_USERNAME }}
SF_JWT_KEY: ${{ secrets.SF_JWT_KEY }}
run: |
printf '%s' "$SF_JWT_KEY" > server.key
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username "$SF_USERNAME" \
--instance-url https://login.salesforce.com \
--alias prod
rm -f server.key
- name: Quick deploy
env:
JOB_ID: ${{ inputs.job_id }}
run: |
case "$JOB_ID" in
0Af*) ;;
*) echo "Not a deployment ID: $JOB_ID" >&2; exit 1 ;;
esac
sf project deploy quick \
--job-id "$JOB_ID" \
--target-org prod \
--wait 60The input reaches the shell through an environment variable and a pattern check, not through direct interpolation into the script. This keeps a mistyped or hostile input from being run as shell code. The 0Af prefix check also catches the common mistake of pasting a different ID.
Passing the job ID by hand is the simplest approach. To automate the handoff, have the second workflow download the artifact from the first with the GitHub API, or store the ID in a release record. Artifacts expire, so check the retention period against the 10-day quick deploy window. If the artifact expires first, you lose the ID even though the validation is still eligible.
Failure handling in automation
Automated runs fail in ways that manual runs make obvious. Plan for these cases.
- Test failures during validation. The command exits non-zero. Print the component and test failures, as the script above does, so the log is enough to diagnose.
- Expired or ineligible validation.
sf project deploy quickfails when the validation is older than 10 days or did not run tests. Do not retry. Run a new validation and use the new job ID. - Metadata changed after validation. A quick deploy does not read your repository. It promotes what was validated. If someone merged a change after the validation, that change is not in the deployment. Record the commit SHA with the job ID, and have the quick deploy job compare it to the release branch before it proceeds.
- Lock contention. Deployments can fail with row lock errors if scheduled jobs or data loads are running. Retrying the validation is safe because it saves nothing, but a retry after a quick deploy needs a human check of what was deployed.
- Runner timeouts. A CI step that times out does not cancel the deployment in the org. Check
sf project deploy reportbefore starting another deployment.
A small file recording the SHA next to the job ID covers the second case:
printf '{"jobId":"%s","commit":"%s","validatedAt":"%s"}\n' \
"$(cat job-id.txt)" \
"$(git rev-parse HEAD)" \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" > validation-record.jsonCalling the Metadata API directly
Some environments cannot install the CLI, such as a build tool with its own Salesforce integration. The SOAP Metadata API exposes the same operations. The calls to know are:
deploy()withDeployOptions.checkOnlyset totrueto validate. It returns anAsyncResultwith an ID.checkDeployStatus(id, includeDetails)to poll. SetincludeDetailstotrueto get component and test results.deployRecentValidation(validationId)to run the quick deploy. It returns the ID of the new deployment.
The Ant Migration Tool and many third-party CI products wrap these calls. When you evaluate a tool, check that it exposes the quick deploy operation and does not just re-run a full deployment with tests. A tool that only offers "deploy" and "validate" forces you to run the Apex tests twice.
Common mistakes in CI setups
- Validating a different package than you deploy. The validation and the release both need to come from the same manifest and the same commit.
- Using
NoTestRunfor the validation. A validation without tests is not eligible for quick deploy in production. - Letting artifacts expire. Store the job ID somewhere that outlives the quick deploy window.
- Treating a green validation as permanent. It expires after 10 days.
- Running the quick deploy job without a gate. Production changes should need a person to approve them, even when the process is automated.
Exercise
A pipeline validates production on Monday and saves the job ID as a CI artifact with a 7-day retention. The release window is the following Thursday, 10 days after the validation. A teammate merges a small fix to the release branch on Tuesday. List two reasons the Thursday quick deploy job should not just run with the Monday job ID, and say what the pipeline should do instead.
Show answer
First, the artifact has expired (7 days of retention) and the validation is at the edge of the 10-day quick deploy limit, so the ID is probably lost or ineligible. Second, the Tuesday fix is not in the Monday validation, so a quick deploy would leave it out of production without anyone noticing. The pipeline should record the commit SHA with the job ID and refuse to proceed when the SHA differs from the release branch. It should then run a new validation with the current commit and quick deploy that new job ID, with the artifact retention set longer than the quick deploy window.
Exercise
Why does the validation script in this chapter avoid set -e, and why does it write job-id.txt even when validation fails?
Show answer
With set -e, the script would exit as soon as sf project deploy validate returned a non-zero status, so the failure details would never print. The script captures the exit status and prints the component and test failures first, then exits with the same status. It writes the job ID on failure because a failed validation still has an ID, which you can pass to sf project deploy report to look at the full results later.