[CI/CD] Github Actions actions/github-script에서 별도 파일을 실행하기
Github Actions actions/github-script에서 별도 파일을 실행하기
환경
- Github Actions
- JavaScript
배경
- yq 혹은 코드를 통해 GitHub Actions에 있는 workflow YAML 파일을 동적으로 수정했을 때 코드가 큰따옴표(“”)로 감싸지는 현상이 있어서, 코드 파일을 바깥으로 빼고 호출하는 형태로 변경한 사례가 있어서 정리함.
actions/github-script
를 사용해봤는데 앞으로도 종종 사용할거 같아서 정리함.
방법
- 사용법은 공식 문서에 나와 있었다.
- 일반적인 JavaScript의 호출 및 사용법과 같다.
예시
코드
github-script-file-return-test.yml
name: Github Script Return Test Workflow
on:
push:
branches: [ main ]
workflow_dispatch:
jobs:
print-complete-event:
name: print complete event
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Get jobs for the current workflow run
id: workflow_result
uses: actions/github-script@v7
with:
script: |
const exportedModule = require('.github/workflows/scripts/github-script-file-test.js');
return exportedModule.processValue(github, context);
- name: Print return values
run: |
echo "${{ fromJSON(steps.workflow_result.outputs.result).data }}"
github-script-file-test.js
function processValue(github, context) {
console.log(JSON.stringify(context));
return {"data": context.workflow};
};
module.exports = {
processValue
};
결과
Run echo "Github Script Return Test Workflow"
echo "Github Script Return Test Workflow"
shell: /usr/bin/bash -e {0}
Github Script Return Test Workflow
기타
- 문서에 보면 사용할 수 있는 미리 만들어진 객체들이 있다.
- github: A pre-authenticated octokit/rest.js client with pagination plugins
- context: An object containing the context of the workflow run
- core: A reference to the @actions/core package
- glob: A reference to the @actions/glob package
- io: A reference to the @actions/io package
- exec: A reference to the @actions/exec package
- require: A proxy wrapper around the normal Node.js require to enable requiring relative paths (relative to the - - current working directory) and requiring npm packages installed in the current working directory. If for some reason you need the non-wrapped require, there is an escape hatch available: original_require is the original value of require without our wrapping applied.
actions/github-script
사용시에 코드가 길어질 경우 포맷팅도 할 수 없고 관리가 어려워질거 같아서 외부 파일로 분리했다.- 일반 JavaScript 사용법과 사실 똑같다.