[CI/CD](EN) Usage of running a separate file in Github Actions actions/github-script
Usage of running a separate file in Github Actions actions/github-script
Environment and Prerequisite
- Github Actions
- JavaScript
Background
- I encountered an issue where code was being wrapped in double quotes (“”) when dynamically modifying workflow YAML files in GitHub Actions using yq or code so I extracted the code files and called that instead.
- I once applied
actions/github-script
and since I think I’ll be using it often in the future. So I decided to write it.
Usage
- The official document provides the instructions.
- It is similar to the usual way of using JavaScript.
Example
Code
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
};
Result
Run echo "Github Script Return Test Workflow"
echo "Github Script Return Test Workflow"
shell: /usr/bin/bash -e {0}
Github Script Return Test Workflow
Others
- The document introduces pre-built objects that you can use.
- 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.
- When using
actions/github-script
, I separated the code into an external file because if the code gets too long, it becomes difficult to format and manage. - It is actually the same as using regular JavaScript.