GitHub actions inputs don't get printed with echo - github

I've been trying to set up the most basic GitHub action that can be triggered via API, and I managed to trigger it, but now I'm having trouble passing down the "inputs" and using them in the jobs...
I tried reading the documentation and all, and it should work but I'm probably missing some syntax or something...
Here's the action code:
name: Test
on:
repository_dispatch:
inputs:
body:
default: 'testdefaultvalue'
description: 'Test desc'
required: true
jobs:
print_inputs:
runs-on: ubuntu-latest
steps:
- name: Print inputs
run: echo "The inputs are ${{ inputs.body }}"
And here's the body that I'm trying to send using POST which hits and triggers this action
{"event_type": "my_event", "client_payload": {"body": "Hello, world!"}}
I keep getting only the first part of the echo, like on this screenshot
I even tried just printing out the inputs body with the default value using a different kinds of syntaxes but nothing worked. Hopefully, this is not a duplicate and someone will help me and it'll be useful for someone in the future as well!

According to repository_dispatch, you need to refer to the complete event context to get the values.
So, this should work in your case:
echo ${{ github.event.client_payload.body }}

Related

GitHub Actions yml Syntax

I am new to GitHub actions and for a few days I have been trying to set up a simple action workflow. I tried searching everywhere about the errors, went through some action workflow syntax documentation by GitHub but still I am not able to figure out anything.
I am trying to use this action template: https://github.com/marketplace/actions/jelastic-github-actions
I just copied and pasted the sample code given in the repo and filled in necessary values but there is always at least one error that keeps popping up.
What is wrong with the yml syntax below (this is exact sample code):
- name: Run GetEnv command
uses: abhisek91/github-actions-jelastic#master
with:
jelastic_url: app.mycloud.by
jelastic_username: ${{ secrets.JELASTIC_USERNAME }}
jelastic_password: ${{ secrets.JELASTIC_TOKEN }}
task: environment/control/getenvs
Github is showing me Invalid type found: object was expected but an array was found for the above code and I don't know what it means.

GitHub Actions: How to view inputs for workflow_dispatch?

My idea here is to write my inputs from workflow_dispatch on each pipeline run. .
For example, in Bitbucket pipelines input parameters shown after custom -
Is there a way to do something similar for GitHub?
Although this does not directly answer your question, I'm adding it here because this is where I landed looking for the answer on how to output all my workflow inputs.
In my case I am using a workflow_dispatch trigger - YMMV if you are using a different trigger, but I suspect it would work the same way.
As with the other answer proposed, you will need to do this as a step within your job:
on:
workflow_dispatch:
inputs:
myInput:
default: "my input value"
jobs:
myJob:
steps:
- name: Output Inputs
run: echo "${{ toJSON(github.event.inputs) }}"
This will result in output you can view in your GitHub action execution output with the inputs serialized as JSON:
{
"myInput": "my input value"
}
If you have only a few simple input values (from workflow_dispatch) then you can include them in the name of the job:
on:
workflow_dispatch:
inputs:
my_value:
description: 'My input value'
required: true
default: 'foo'
type: string
jobs:
my_job:
name: "My job [my_value: ${{ github.event.inputs.my_value }}]"
runs-on: ubuntu-latest
steps:
....
This way you will be able to see the input directly in the GitHub UI.
You cannot really alter how they will be displayed on the list I'm afraid.
All you can do is to log your input variables inside action itself, like this:
jobs:
debugInputs:
runs-on: ubuntu-latest
steps:
- run: |
echo "Var1: ${{ github.event.inputs.var1 }}"
echo "Var2: ${{ github.event.inputs.var2 }}"
If you want to see them in summary, you can use a notice or warning message mark:
I was looking for something similar and landed on logging + writing to the Job Summary.
I created a small action that can easily be used as a first step in your workflow, since I found myself need

How to create a dropdown in a GitHub action job

My job needs to receive 2 input parameter from the user.
Valid values of those parameters are defined by a separate script. These values can change (not able to hard code them) so I want to populate the list dynamically when the job is to be run. The picker should update according to the result of the script allowing the user to select and only then should the actual job be run with those values as input to the job
Question is how to provide a drop down like that
Since Nov. 2021, the input type can actually be a choice list.
GitHub Actions: Input types for manual workflows
You can now specify input types for manually triggered workflows allowing you to provide a better experience to users of your workflow.
In addition to the default string type, we now support choice, boolean, and environment.
name: Mixed inputs
on:
workflow_dispatch:
inputs:
name:
type: choice
description: Who to greet
options:
- monalisa
- cschleiden
message:
required: true
use-emoji:
type: boolean
description: Include 🎉🤣 emojis
environment:
type: environment
jobs:
greet:
runs-on: ubuntu-latest
steps:
- name: Send greeting
run: echo "${{ github.event.inputs.message }} ${{ fromJSON('["", "🥳"]')[github.event.inputs.use-emoji == 'true'] }} ${{ github.event.inputs.name }}"
That would provide a dropdown.
The question remains: can you pass a list of choices as variable to your input choice field?
You should, if you can populate the inputs context, through another job (computing your list), and calling your choice job, passing the list through jobs.<job_id>.with / jobs.<job_id>.with.<input_id>

How to get pull request number within GitHub Actions workflow

I want to access the Pull Request number in a Github Actions workflow. I can access the GITHUB_REF environment variable that is available. Although on a Pull Request action it has the value: "refs/pull/125/merge". I need to extract just the "125".
I have found a similar post here that shows how to get the current branch using this variable. Although in this case, what I am parsing is different and I have been unable to isolate the Pull Request number.
I have tried using {GITHUB_REF##*/} which resolves to "merge"
I have also tried {GITHUB_REF#*/} which resolves to "pull/125/merge"
I only need the Pull Request number (which in my example is 125)
Although it is already answered, the easiest way I found is using the github context. The following example shows how to set it to an environment variable.
env:
PR_NUMBER: ${{ github.event.number }}
An alternative if you are trying to figure out which PR a commit is linked to on a push instead of a pull_request event is to use the gh CLI which is included in the standard GitHub Action images.
For example:
- name: Get Pull Request Number
id: pr
run: echo "::set-output name=pull_request_number::$(gh pr view --json number -q .number || echo "")"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Be sure to add pull_request: read permissions on the job as well.
Then in following steps, you can access it with the variable,
${{ steps.pr.outputs.pull_request_number }}
While the answer by #Samira worked correctly. I found out that there is a new way to do this and wanted to share it with anyone who might stumble upon this.
The solution is to add a stage at the beginning of your workflow which gets the PR number from the Github Token (event) and then set it as an environment variable for easy use throughout the rest of the workflow. Here is the code:
- name: Test
uses: actions/github-script#0.3.0
with:
github-token: ${{github.token}}
script: |
const core = require('#actions/core')
const prNumber = context.payload.number;
core.exportVariable('PULL_NUMBER', prNumber);
Now in any later stage, you can simply use $PULL_NUMBER to access the environment variable set before.
How about using awk to extract parts of GITHUB_REF instead of bash magick?
From awk manpage:
-F fs
--field-separator fs
Use fs for the input field separator (the value of the FS predefined variable).
As long you remember this, it's trivial to extract only part of variable you need. awk is available on all platforms, so step below will work everywhere:
- run: echo ::set-env name=PULL_NUMBER::$(echo "$GITHUB_REF" | awk -F / '{print $3}')
shell: bash
Just gonna drop what worked out for me
- id: find-pull-request
uses: jwalton/gh-find-current-pr#v1
with:
# Can be "open", "closed", or "all". Defaults to "open".
state: open
- name: create TODO/FIXME comment body
id: comment-body
run: |
yarn leasot '**/*.{js,ts,jsx,tsx}' --ignore 'node_modules/**/*' --exit-nicely --reporter markdown > TODO.md
body="$(sed 1,2d TODO.md)"
body="${body//'%'/'%25'}"
body="${body//$'\n'/'%0A'}"
body="${body//$'\r'/'%0D'}"
echo "::set-output name=body::$body"
- name: post TODO/FIXME comment to PR
uses: peter-evans/create-or-update-comment#v2
with:
issue-number: ${{ steps.find-pull-request.outputs.number }}
body: ${{ steps.comment-body.outputs.body }}
Here's a working snippet to get the issue number in both push and pull_request events within a GitHub Actions workflow by leveraging actions/github-script:
steps:
- uses: actions/github-script#v6
id: get_issue_number
with:
script: |
if (context.issue.number) {
// Return issue number if present
return context.issue.number;
} else {
// Otherwise return issue number from commit
return (
await github.rest.repos.listPullRequestsAssociatedWithCommit({
commit_sha: context.sha,
owner: context.repo.owner,
repo: context.repo.repo,
})
).data[0].number;
}
result-encoding: string
- name: Issue number
run: echo '${{steps.get_issue_number.outputs.result}}'
The script queries the list labels for an issue REST API endpoint via octokit/rest.js client.

Using output from a previous job in a new one in a GitHub Action

For (mainly) pedagogical reasons, I'm trying to run this workflow in GitHub actions:
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
produce_comment:
name: Respond to issue
runs-on: ubuntu-latest
steps:
- name: Dump job context
env:
JOB_CONTEXT: ${{ jobs.maybe-greet.steps.id }}
run: echo "$JOB_CONTEXT"
I need two different jobs, since they use different context (operating systems), but I need to get the output of a step in the first job to the second job. I am trying with several combinations of the jobs context as found here but there does not seem to be any way to do that. Apparently, jobs is just the name of a YAML variable that does not really have a context, and the context job contains just the success or failure. Any idea?
Check the "GitHub Actions: New workflow features" from April 2020, which could help in your case (to reference step outputs from previous jobs)
Job outputs
You can specify a set of outputs that you want to pass to subsequent jobs and then access those values from your needs context.
See documentation:
jobs.<jobs_id>.outputs
A map of outputs for a job.
Job outputs are available to all downstream jobs that depend on this job.
For more information on defining job dependencies, see jobs.<job_id>.needs.
Job outputs are strings, and job outputs containing expressions are evaluated on the runner at the end of each job. Outputs containing secrets are redacted on the runner and not sent to GitHub Actions.
To use job outputs in a dependent job, you can use the needs context.
For more information, see "Context and expression syntax for GitHub Actions."
To use job outputs in a dependent job, you can use the needs context.
Example
jobs:
job1:
runs-on: ubuntu-latest
# Map a step output to a job output
outputs:
output1: ${{ steps.step1.outputs.test }}
output2: ${{ steps.step2.outputs.test }}
steps:
- id: step1
run: echo "test=hello" >> $GITHUB_OUTPUT
- id: step2
run: echo "test=world" >> $GITHUB_OUTPUT
job2:
runs-on: ubuntu-latest
needs: job1
steps:
- run: echo ${{needs.job1.outputs.output1}} ${{needs.job1.outputs.output2}}
Note the use of $GITHUB_OUTPUT, instead of the older ::set-output now (Oct. 2022) deprecated.
To avoid untrusted logged data to use set-state and set-output workflow commands without the intention of the workflow author we have introduced a new set of environment files to manage state and output.
Jesse Adelman adds in the comments:
This seems to not work well for anything beyond a static string.
How, for example, would I take a multiline text output of step (say, I'm running a pytest or similar) and use that output in another job?
either write the multi-line text to a file (jschmitter's comment)
or base64-encode the output and then decode it in the next job (Nate Karasch's comment)
Update: It's now possible to set job outputs that can be used to transfer string values to downstream jobs. See this answer.
What follows is the original answer. These techniques might still be useful for some use cases.
Write the data to file and use actions/upload-artifact and actions/download-artifact. A bit awkward, but it works.
Create a repository dispatch event and send the data to a second workflow. I prefer this method personally, but the downside is that it needs a repo scoped PAT.
Here is an example of how the second way could work. It uses repository-dispatch action.
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
- name: Repository Dispatch
uses: peter-evans/repository-dispatch#v1
with:
token: ${{ secrets.REPO_ACCESS_TOKEN }}
event-type: my-event
client-payload: '{"greet": "${{ steps.maybe-greet.outputs.GREET }}"}'
This triggers a repository dispatch workflow in the same repository.
name: Repository Dispatch
on:
repository_dispatch:
types: [my-event]
jobs:
myEvent:
runs-on: ubuntu-latest
steps:
- run: echo ${{ github.event.client_payload.greet }}
In my case I wanted to pass an entire build/artifact, not just a string:
name: Build something on Ubuntu then use it on MacOS
on:
workflow_dispatch:
# Allows for manual build trigger
jobs:
buildUbuntuProject:
name: Builds the project on Ubuntu (Put your stuff here)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- uses: some/compile-action#v99
- uses: actions/upload-artifact#v2
# Upload the artifact so the MacOS runner do something with it
with:
name: CompiledProject
path: pathToCompiledProject
doSomethingOnMacOS:
name: Runs the program on MacOS or something
runs-on: macos-latest
needs: buildUbuntuProject # Needed so the job waits for the Ubuntu job to finish
steps:
- uses: actions/download-artifact#master
with:
name: CompiledProject
path: somewhereToPutItOnMacOSRunner
- run: ls somewhereToPutItOnMacOSRunner # See the artifact on the MacOS runner
It is possible to capture the entire output (and return code) of a command within a run step, which I've written up here to hopefully save someone else the headache. Fair warning, it requires a lot of shell trickery and a multiline run to ensure everything happens within a single shell instance.
In my case, I needed to invoke a script and capture the entirety of its stdout for use in a later step, as well as preserve its outcome for error checking:
# capture stdout from script
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code as well
SCRIPT_RC=$?
# FYI, this would get stdout AND stderr
SCRIPT_ALL_OUTPUT=$(./do-something.sh 2>&1)
Since Github's job outputs only seem to be able to capture a single line of text, I also had to escape any newlines for the output:
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
Additionally, I needed to ultimately return the script's exit code to correctly indicate whether it failed. The whole shebang ends up looking like this:
- name: A run step with stdout as a captured output
id: myscript
run: |
# run in subshell, capturiing stdout to var
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code too
SCRIPT_RC=$?
# print a single line output for github
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
# exit with the script status
exit $SCRIPT_RC
continue-on-error: true
- name: Add above outcome and output as an issue comment
uses: actions/github-script#v5
env:
STEP_OUTPUT: ${{ steps.myscript.outputs.stdout }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// indicates whather script succeeded or not
let comment = `Script finished with \`${{ steps.myscript.outcome }}\`\n`;
// adds stdout, unescaping newlines again to make it readable
comment += `<details><summary>Show Output</summary>
\`\`\`
${process.env.STEP_OUTPUT.replace(/\\n/g, '\n')}
\`\`\`
</details>`;
// add the whole damn thing as an issue comment
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
})
Edit: there is also an action to accomplish this with much less bootstrapping, which I only just found.
2022 October update: GitHub is deprecating set-output and recommends to use GITHUB_OUTPUT instead. The syntax for defining the outputs and referencing them in other steps, jobs.
An example from the docs:
- name: Set color
id: random-color-generator
run: echo "SELECTED_COLOR=green" >> $GITHUB_OUTPUT
- name: Get color
run: echo "The selected color is ${{ steps.random-color-generator.outputs.SELECTED_COLOR }}"