How to Create a GitHub Deployment for a Preview in GitHub Actions
Call createDeployment and createDeploymentStatus so the PR displays a first-class environment entry with the preview URL.
The Deployments API turns a preview into a tracked environment on the PR. Create a deployment for the head ref, then post a success status with the environment_url. Grant deployments: write.
Steps
- Grant
deployments: writeto the job. - Call
createDeploymentfor the PR head ref with an environment name. - Post
createDeploymentStatuswith statesuccessandenvironment_url.
Workflow
.github/workflows/preview.yml
permissions:
deployments: write
jobs:
record:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const dep = await github.rest.repos.createDeployment({
owner: context.repo.owner, repo: context.repo.repo,
ref: context.payload.pull_request.head.sha,
environment: 'preview',
auto_merge: false, required_contexts: [],
})
await github.rest.repos.createDeploymentStatus({
owner: context.repo.owner, repo: context.repo.repo,
deployment_id: dep.data.id,
state: 'success',
environment_url: process.env.PREVIEW_URL,
})
env:
PREVIEW_URL: ${{ needs.preview.outputs.url }}Gotchas
- Set
required_contexts: []or the deployment stays pending on missing checks. - Post an
inactivestatus on teardown so the environment stops showing as live.
Related guides
How to Post the Preview URL as a PR Comment in GitHub ActionsComment a deployed preview URL on the pull request from GitHub Actions with actions/github-script, updating a…
How to Tear Down a Preview Environment When a PR Closes in GitHub ActionsAutomatically destroy a per-PR preview environment when the pull request is closed or merged in GitHub Action…