如何通过HTTP请求向GitHub Actions Workflow发送数据载荷并在工作流中使用
带自定义载荷触发GitHub Actions Workflow实现方案
1. 调整curl请求添加自定义参数
你当前使用的是workflow_dispatch对应的API接口,只需在POST请求的-d参数的JSON结构中新增inputs字段,即可传入自定义载荷:
curl \ -X POST \ -H "Accept: application/vnd.github.v3+json" \ --header 'Authorization: token ******' \ https://api.github.com/repos/aashutosh0012/actions-test/actions/workflows/learn-github-actions.yml/dispatches \ -d '{"ref":"main","inputs":{"username":"test_user","content":"自定义测试内容"}}'
上述inputs下的键值对就是自定义载荷数据,可根据业务需求自行增减字段。
如果你使用
repository_dispatch方式触发,需要调用仓库的dispatches接口,请求示例如下:curl \ -X POST \ -H "Accept: application/vnd.github.v3+json" \ --header 'Authorization: token ******' \ https://api.github.com/repos/aashutosh0012/actions-test/dispatches \ -d '{"event_type": "custom_trigger", "client_payload": {"username":"test_user","content":"自定义内容"}}'
2. 调整Workflow配置接收并使用载荷
- 若使用
workflow_dispatch触发,需要先在触发条件中声明接收的参数定义,之后通过${{ github.event.inputs.参数名 }}格式调用载荷 - 若使用
repository_dispatch触发,直接通过${{ github.event.client_payload.参数名 }}格式调用载荷即可
3. 完整修改后的Workflow参考
name: GitHub Actions Demo # 声明触发条件,给workflow_dispatch添加输入参数定义 on: push: workflow_dispatch: inputs: username: description: '自定义传入的用户名' required: true type: string content: description: '自定义传入的内容' required: false type: string default: '默认内容' repository_dispatch: jobs: Explore-GitHub-Actions: runs-on: ubuntu-latest steps: - run: echo "🎉 本次任务由 ${{ github.event_name }} 事件触发" # 直接调用传入的载荷数据 - run: echo "传入的用户名是 ${{ github.event.inputs.username }},传入的内容是 ${{ github.event.inputs.content }}" - run: echo "🐧 任务运行在GitHub托管的${{ runner.os }} 服务器上" - run: echo "🔎 当前分支是 ${{ github.ref }},仓库名是 ${{ github.repository }}" - name: 拉取仓库代码 uses: actions/checkout@v2 - run: echo "💡 仓库 ${{ github.repository }} 已克隆到运行器" - run: echo "🖥️ 工作流已准备好在运行器上测试代码" - name: 列出仓库文件 run: | ls ${{ github.workspace }} - run: echo "🍏 任务当前状态为 ${{ job.status }}" - uses: actions/setup-python@v2 with: python-version: '3.x' architecture: 'x64' # 将载荷参数传入Python脚本的示例 - name: 运行Python脚本并传入参数 run: python test.py "${{ github.event.inputs.username }}" "${{ github.event.inputs.content }}" - name: 安装Python依赖 run: | python -m pip install --upgrade pip pip install requests Flask pip list
如果需要在Python脚本中读取传入的载荷参数,可直接通过sys.argv读取:
# test.py 示例代码 import sys if __name__ == '__main__': username = sys.argv[1] content = sys.argv[2] print(f"收到传入的参数:用户名{username},内容{content}")
内容的提问来源于stack exchange,提问作者Aashutosh Kumar
相关产品推荐
相关产品推荐

