如何在ServiceNow变更请求创建中动态填充start_date字段?
问题
我有一个包含多个任务的GitHub Actions工作流,其中集成了ServiceNow变更请求创建流程。在ServiceNow变更请求的JSON负载里,start_date字段需要填充当前UTC时间,但目前是手动硬编码的,很不方便。
我的工作流片段如下:
Snow-Change-Creation: name: Snow-Change-Creation needs: [Previous Job Name] runs-on: ubuntu-latest steps: - name: ServiceNow Change Request Creation uses: ServiceNow/servicenow-devops-change@v3.1.0 with: devops-integration-token: ${{ secrets.SN_..._TOKEN }} instance-url: ${{ secrets.SN_..._INSTANCE_URL }} tool-id: ${{ secrets.SN_..._TOOL_ID }} context-github: ${{ toJSON(github) }} job-name: 'Snow-Change-Creation' change-request: '{ "setCloseCode":"true", "autoCloseChange":"true", "attributes":{ ... "start_date": "2024-04-05 06:28:00" } }'
我尝试过用github.run_started_at但没生效,还试过引用前序任务的输出:
change-request: '{ "setCloseCode":"true", "autoCloseChange":"true", "attributes":{ ... "start_date": "needs.previous-job.outputs.<output-name>" } }'
前序任务的配置是:
.previous-job: runs-on: ubuntu-latest # outputs to share with other jobs outputs: output-name: ${{ steps.get_utctime.outputs.time_output }} - id: get_utctime run: echo "time_output=$(date +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_OUTPUT
想找个可靠的方法或变通方案实现动态填充当前UTC时间到start_date字段。
解决方案
方法1:在当前步骤直接生成UTC时间
无需依赖前序任务,直接在Snow-Change-Creation任务中新增步骤生成UTC时间,再在ServiceNow步骤中引用:
Snow-Change-Creation: name: Snow-Change-Creation needs: [Previous Job Name] runs-on: ubuntu-latest steps: - name: 获取当前UTC时间 id: get_utc_time run: echo "utc_time=$(date -u +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_OUTPUT # -u 参数强制输出UTC时间 - name: ServiceNow Change Request Creation uses: ServiceNow/servicenow-devops-change@v3.1.0 with: devops-integration-token: ${{ secrets.SN_..._TOKEN }} instance-url: ${{ secrets.SN_..._INSTANCE_URL }} tool-id: ${{ secrets.SN_..._TOOL_ID }} context-github: ${{ toJSON(github) }} job-name: 'Snow-Change-Creation' change-request: '{ "setCloseCode":"true", "autoCloseChange":"true", "attributes":{ ... "start_date": "${{ steps.get_utc_time.outputs.utc_time }}" } }'
方法2:修正前序任务输出的引用方式
你之前的问题是引用前序任务输出时未使用GitHub Actions表达式语法,正确的引用需要用${{ ... }}包裹。同时要确保前序任务生成的是UTC时间:
修正后的前序任务
.previous-job: runs-on: ubuntu-latest outputs: output-name: ${{ steps.get_utctime.outputs.time_output }} steps: - id: get_utctime run: echo "time_output=$(date -u +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_OUTPUT
修正后的ServiceNow步骤引用
change-request: '{ "setCloseCode":"true", "autoCloseChange":"true", "attributes":{ ... "start_date": "${{ needs.previous-job.outputs.output-name }}" } }'
方法3:正确使用github.run_started_at
github.run_started_at默认是ISO 8601格式(如2024-04-05T06:28:00Z),只需用format函数转换为ServiceNow需要的格式即可:
change-request: '{ "setCloseCode":"true", "autoCloseChange":"true", "attributes":{ ... "start_date": "${{ format(''%Y-%m-%d %H:%M:%S'', github.run_started_at) }}" } }'
这个方法无需额外步骤,直接利用GitHub内置上下文变量,是最简洁的实现方式。
内容的提问来源于stack exchange,提问作者mas
相关产品推荐
相关产品推荐

