|
| 1 | +--- |
| 2 | +type: post |
| 3 | +title: How to set GitHub job environment dynamically? |
| 4 | +date: 2023-02-28T17:13:57+07:00 |
| 5 | +author: ansidev |
| 6 | +gravatar: a2ac3c4477e717c7fa15041d907e71fd |
| 7 | +twitter: "@ansidev" |
| 8 | +permalink: /github-actions/how-to-set-github-job-environment-dynamically |
| 9 | +categories: |
| 10 | + - DevOps |
| 11 | + - CI/CD |
| 12 | + - GitHub Actions |
| 13 | +tags: |
| 14 | + - job environment |
| 15 | +--- |
| 16 | + |
| 17 | +This is how I set the GitHub Actions job environment dynamically. |
| 18 | + |
| 19 | +## Solutions |
| 20 | + |
| 21 | +```yaml |
| 22 | +name: deploy |
| 23 | + |
| 24 | +on: |
| 25 | + pull_request: |
| 26 | + branches: |
| 27 | + - main |
| 28 | + - develop |
| 29 | + types: |
| 30 | + - opened |
| 31 | + - synchronize |
| 32 | + - closed |
| 33 | + |
| 34 | +jobs: |
| 35 | + set_job_environment: |
| 36 | + if: github.event.action != 'closed' || |
| 37 | + github.event.pull_request.merged == true |
| 38 | + runs-on: ubuntu-latest |
| 39 | + steps: |
| 40 | + - name: Set job environment as pr-${{ github.event.number }} |
| 41 | + if: github.base_ref == 'develop' && |
| 42 | + contains(fromJSON('["opened", "synchronize"]'), github.event.action) |
| 43 | + env: |
| 44 | + JOB_ENVIRONMENT: pr-${{ github.event.number }} |
| 45 | + run: | |
| 46 | + echo "JOB_ENVIRONMENT=$JOB_ENVIRONMENT" >> $GITHUB_ENV |
| 47 | +
|
| 48 | + - name: Set job environment as preview |
| 49 | + if: github.base_ref == 'develop' && |
| 50 | + github.event.action == 'closed' && |
| 51 | + github.event.pull_request.merged == true |
| 52 | + run: | |
| 53 | + echo "JOB_ENVIRONMENT=preview" >> $GITHUB_ENV |
| 54 | +
|
| 55 | + - name: Set job environment as staging |
| 56 | + if: github.base_ref == 'main' && |
| 57 | + contains(fromJSON('["opened", "synchronize"]'), github.event.action) |
| 58 | + run: | |
| 59 | + echo "JOB_ENVIRONMENT=staging" >> $GITHUB_ENV |
| 60 | +
|
| 61 | + - name: Set job environment as production |
| 62 | + if: github.base_ref == 'main' && |
| 63 | + github.event.action == 'closed' && |
| 64 | + github.event.pull_request.merged == true |
| 65 | + run: echo "JOB_ENVIRONMENT=production" >> $GITHUB_ENV |
| 66 | + |
| 67 | + - name: Set job environment output |
| 68 | + id: job_environment |
| 69 | + run: | |
| 70 | + echo "github_environment=$JOB_ENVIRONMENT" >> $GITHUB_OUTPUT |
| 71 | +
|
| 72 | + outputs: |
| 73 | + github_environment: ${{ steps.job_environment.outputs.github_environment }} |
| 74 | + |
| 75 | + deploy: |
| 76 | + needs: set_job_environment |
| 77 | + environment: |
| 78 | + name: ${{ needs.set_job_environment.outputs.github_environment }} |
| 79 | + # Other configurations |
| 80 | +``` |
| 81 | + |
| 82 | +## References |
| 83 | + |
| 84 | +- [GitHub Actions Runner Issue](https://github.com/actions/runner/issues/998). |
0 commit comments