Using github.inputs and variables in workflows - github

So basically what I try to do is as following
if there is a push to repository A trigger the pipeline of repository B with an input thatis the the name of the branch in repository A that is pushed to. Lets call it $branchname
So what I did was a bit googling and saw that I need to add a workflow_dispatch in the B's workflow file and add some inputs. That work nice. But...
I still want people to be able to push to repository B from branches in B and trigger its pipeline with $branchname equal to a value of "dev".
I did the following in
jobs:
build:
steps:
uses: ...
....
- name: my script
run: |
if [[ -v ${{ inputs.branchname }} ]]; then value=${{ inputs.branchname }};else value="dev"; fi
...
But in the code above the value of branchname is empty for pushes from repository B. Since ${{ inputs.branchname }} is empty. So i need to find a way to be able to map the workflow_dispatch variable to a env variable to be able to use it regardless if the push is in repo A or repo B.
Do you know any way?
Please help.
Thanks in advance

I solved the problem by:
jobs:
build:
steps:
uses: ...
....
- name: my script
run: |
my__first_var=${{ inputs.branchname }}
if [[ -v my_var ]];
my_second_var="$my__first_var"
else
my_second_var="dev"
fi
...

Related

Cannot retrieve and display Github env setup in previous step

I am trying to setup a variable in my CI pipeline that I will reuse later (eventually in another job, which I don't know if possible since I don't know if jobs shares variables.. but this is another problem). My pipeline is:
name: CI
on:
pull_request:
branches:
- main
jobs:
test-job:
runs-on: ubuntu-latest
name: test-job
steps:
- name: setup env variable
run: |
BRANCH_NAME=`echo "${{github.head_ref}}"'`
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
echo ${{ env.BRANCH_NAME }}
that last echo doesn't show anything unfortunately. I am sure that BRANCH_NAME is correctly set because before pushing it into the $GITHUB_ENV" I did echo it and it contains data. Plus you can see the name of the branch in the console logs.
Console logs from Github are the following:
1. Run BRANCH_NAME=`echo "test_branch"'`
2. BRANCH_NAME=test_branch >> /home/runner/work/_temp/_runner_file_commands/set_env_9eeeac39-f573-4079-ba62-e1c2019f7aff
3.
So, that final echo ${{ env.BRANCH_NAME }} gives no result. What am I missing?
UPDATE:
As suggested in the comments, I started using workflow variables, in such a way that they are available throughout all the jobs.
The initial setup becomes:
name: CI
on:
pull_request:
branches:
- main
env:
BRANCH_NAME: ""
jobs:
...
I don't like the fact I need to give those variables an empty string value as placeholder and would have preferred declaring and assigning them in one of the jobs itself.. but still. So, now variables are declared before the jobs section, how do I assign a value to them in one of my steps? Meaning, I need to replace the
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
tried already
echo "BRANCH_NAME=$BRANCH_NAME >> ${{ env.BRANCH_NAME }}
or
${{ env.BRANCH_NAME }}=$BRANCH_NAME
but both ways don't work.

github actions | get origin branch on push

I want that a workflow that starts on push will print the origin (base) branch name and name of the one who did the push.
for example if my name is Tom and I merged 'test' branch to master, I will be able to get 'Tom' and 'test' as values on the workflow that starts on push (right after the pull request).
I did find something that works on pull request to get the base branch name: ${{ github.event.pull_request.head.ref }}, but when replacing 'pull_request' with push it doesn't work anymore.
Is there a way to do it?
I've been searching for hours now and can't find a proper solution, for each type of event there is a different solution.
Thank you for reading!
You can use the following properties of the github context:
github.ref_name
github.event.pusher.name (see: push event payload)
Here is an example of a complete workflow:
name: show-push-info
on:
push:
jobs:
print-info:
runs-on: ubuntu-latest
steps:
- name: Print info
run: echo "'${{ github.ref_name }}' was pushed by '${{ github.event.pusher.name }}'"

GitHub actions: default branch variable

Is there any smart way to determine the default branch in GitHub actions?
Now I need to write something like:
on:
push:
branches:
- master
is there a way to write something like the code below?
on:
push:
branches:
- $default-branch
I tried to google but found nothing
I accidentally found a really nice way to solve this. That evalutes to the branch name, e.g. master.
${{ github.event.repository.default_branch }}
Also, found out the hard way that that always() is side-effecting: my job was getting skipped if always() was not called even though the other clause was true.
This works to run a job only when running on default branch
if: ${{ always() && format('refs/heads/{0}', ) == github.ref }}
$default-branch can be used in Workflow templates, but not in Workflows. The branch will become hard-coded in the Workflow upon initialization, and will have to be manually maintained. [1]
Blog post: https://github.blog/changelog/2020-07-22-github-actions-better-support-for-alternative-default-branch-names/
- if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
run: echo "On the default branch"
- if: github.ref != format('refs/heads/{0}', github.event.repository.default_branch)
run: echo "Not on the default branch"
This is not possible at the moment. Please check this topic on github community
You simply can reach variable at this level
The workflow is not valid. .github/workflows/so-004-variables-in-trigger.yaml (Line: 7, Col: 9): Unrecognized named-value: 'env'. Located at position 1 within expression: env.default-branch
You may consider addition filterint based on the branch name like here but at the moment you can't do what you want.
Add this step to your job:
- name: Determine default branch
run: |
DEFAULT_BRANCH=$(git remote show origin | awk '/HEAD branch/ {print $NF}')
echo "default_branch=$DEFAULT_BRANCH" >> $GITHUB_ENV
echo "default_branch_ref=refs/heads/$DEFAULT_BRANCH" >> $GITHUB_ENV
That will add a default_branch and a default_branch_ref variable to the env enivronment variables.
You can then access the default branch name with ${{ env.default_branch }} in subsequent steps.
The default_branch_ref variable is useful for directly comparing against github.ref to determine whether you are on the default branch.
This method uses the current method of setting environment variables to use in later steps [1] and JoeLinux's method for determining the default branch name [2].
Full example workflow:
name: ci
on: [push, pull_request]
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Determine default branch
run: |
DEFAULT_BRANCH=$(git remote show origin | awk '/HEAD branch/ {print $NF}')
echo "default_branch=$DEFAULT_BRANCH" >> $GITHUB_ENV
echo "default_branch_ref=refs/heads/$DEFAULT_BRANCH" >> $GITHUB_ENV
- name: debug
run: echo ${{ env.default_branch }}
- name: Deploy
if: github.ref == env.default_branch_ref
run: echo "Run!"
You can use $default-branch in a template, and then when that template is rendered into a new repo, it will be replaced with the (then) default branch name for the repo, but that is a very limited use case and still does not help you when the name of the default branch changes. The best I have come up with is to list the all the default branch names in the organization, like this:
on:
push:
branches:
- master
- main
- root
- default
- production
and then you can either trust that the repos will not have non-default branches with those names, or start the jobs and then filter them by adding an if condition like
if: github.event.push.ref == format('refs/heads/{}', github.event.repository.default_branch)
Side note
For most events
${{ github.event.repository.default_branch }}
is available and works fine, but not when running schedule events via cron. When github.event_name == "schedule" the only element in github.event is schedule (the cron string that triggered the run).
When running inside a GitHub action on at GitHub runner with gh available, this more reliably gets you the default branch name:
gh repo view --json defaultBranchRef --jq .defaultBranchRef.name
However, this does not help the OP when you want to make the default branch the target that triggers the run.
Hopefully, there will be a better way to do this in the future. Until then, you can use the GitHub API and save the result in a named step output.
e.g.
- name: Extract default branch name
shell: bash
run: |
owner="my-org"
repo="repo_x"
branch=$(curl -L -H 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
https://api.github.com/repos/${owner}/${repo} \
| jq .default_branch)
echo "##[set-output name=default_branch;]$(echo ${branch})"
id: repo_x
...
${{ steps.repo_x.outputs.default_branch }}

Getting base branch SHA on pull request in Github Action Workflow

In GitHub action on pull request, I need to run some code in the context of the "current master", and later re-run the same code in the context of the PR branch.
I can check out compare a pull request to the base it is being PR-ed against. How would I find the SHA of the base branch (e.g. current master if PR is against the master)?
jobs:
job_on_base:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
ref: "${{ github.base_ref }}"
- run: |
# Seems like I can get it here with $(git log -1 --format="%H")
echo "My current SHA is ... ?"
job_on_pr:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
ref: "${{ github.ref }}"
- run: |
echo "My current SHA is $GITHUB_SHA"
echo "The BASE SHA is ?"
If the job runs on a pull_request event the base sha is available as ${{ github.event.pull_request.base.sha }}
This turned out to be a git question, rather than Github actions. The actions/checkout#v2 creates a shallow --depth=1 clone, so to get PR's parent one can parse git cat-file -p output as described here. The first (base) parent could be accessed with
git cat-file -p <SHA> | awk 'NR > 1 {if(/^parent/){print $2; exit}}'
The better approach turned out to be using fetch-depth: 2 parameter. It allows just one job to handle both pull request and master merge cases, and can also be used with HEAD^1 to get to the parent.
steps:
- uses: actions/checkout#v2
with:
fetch-depth: 2
What worked for me was: github.event.workflow_run.head_sha.
The top-voted answer suggesting github.event.pull_request.head.sha didn't work for me.
I found this by examining all the possible data in the github.context object using the method suggested here - https://stackoverflow.com/a/70107953

Ways to get last commit author in Github Actions workflow

I am working on converting a Jenkins Pipeline into a Github Actions workflow and need a way of storing the commit author as an environment variable for later use in node.js code.
I have read the documentation and this seems to be the only way I can get it working:
name: Feature Branch PR
on:
pull_request:
types: [opened, edited, synchronize]
push:
branches:
- '**'
Then in the Env section:
env:
AUTHOR: ${{ github.event.pusher.name }}
The problem is this only works for Push triggers. So if i remove the on: push section from top of yml workflow (so it only triggers on PRs) the AUTHOR info becomes empty.
I cannot find a way to get it for commits. Does anyone know of of a way? We do not want this workflow to trigger on pushes.
I also tried
AUTHOR: $(jq '.commits.committer.name' $GITHUB_EVENT_PATH)
I think this was syntactically incorrect though.
For anyone who struggles with this in future, I managed to work it out.
In the node code (not yml) you can obtain an Actions event.json file with all info available. To get the author of a previous commit:
const ev = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'));
return ev.pull_request.user.login;
As YakovL mentioned,
env:
${{ github.event.pull_request.user.login }}
Works fine in a Github action.
To answer the question that was originally asked, you can do the following to get the author of the last commit in a GitHub action:
github.event.commits[0].author.name
For example (to prevent a loop in an action using a personal access token):
name: Version and Package Repo
on:
push:
branches: [ master, main ]
jobs:
build:
if: github.event.commits[0].author.name != 'GitHubActions'
runs-on: ubuntu-18.04
steps:
- name: Checkout repo
uses: actions/checkout#v2
with:
fetch-depth: 0
token: ${{ secrets.PAT }}
- name: Configure git
run: |
git config user.name "GitHubActions"
git config user.email "<>"
- name: Version and Package
run: npm version patch --force
env:
NODE_AUTH_TOKEN: $\{{ secrets.PAT }}
- name: Update git
run: |
git push
git push --tags
You can use this in the interpolation format too:
${github.event.commits[0].author.name}
And if you need to use different github context variables, they are documented at:
https://docs.github.com/en/actions/learn-github-actions/environment-variables
https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#push
Annoyingly, the user details are in different formats for different event types, but in addition to example above (for push), you could try github.event.head.user.login or github.event.base.user.login too