javascriptgithub-actionsbuilding-github-actions

How to get run_id in a Javascript-based GitHub action?


I'm trying to retrieve the run ID from the context object. However, all my attempts are in vain. The output of the following tries is undefined. Here's the relevant snippet:

    const context = core.getInput('github_context');
    if (context) {
      core.info("Context: " + context)
      core.info(`run id: ${context['run_id']}`)
      core.info(`run id: ${context.run_id}`)
      core.info(`run id: ${context['runId']}`)
      core.info(`run id: ${context.runId}`)
    }

When anaysing the output of core.info("Context: " + context), one can see the following:

Context: {
  "token": "**",
  "job": "test",
  "run_id": "123",

The way I pass the context is github_context: ${{ toJson(github) }}


Solution

  • The context variable is a JSON string, not a Javascript object due to which the problem arises. To access its properties, you will need to parse the JSON string first.

    // ...Rest of your code
    const contextString = core.getInput('github_context');
    if (contextString) {
      const context = JSON.parse(contextString); // <--- this
      core.info("Context: " + contextString)
      core.info(`run id: ${context['run_id']}`)
      core.info(`run id: ${context.run_id}`);
    }