How can i get the Passing/Failing status of a Github Action Workflow? - github

I have been looking at the GitHub REST API and i have been trying to find out where I can find the endpoint to get the status of a workflow in my actions. The only way i can tell if it is passing or failing is by downloading the badge.svg.

You can use workflow run api :
GET https://api.github.com/repos/[owner]/[repo]/actions/workflows/[workflowID]/runs
[workflowID] can also be the filename, in the following example ci.yml :
https://api.github.com/repos/bertrandmartel/tableau-scraping/actions/workflows/ci.yml/runs
Then you can get the first run using curl and jq :
curl -s "https://api.github.com/repos/bertrandmartel/tableau-scraping/actions/workflows/ci.yml/runs" | \
jq -r '.workflow_runs[0].status'
output:
completed

Related

How to trigger a `workflow_dispatch` from Github API?

From the GH Rest API docs, seems we're able to create a repository_dispatch event, but no workflow_dispatch event. In the GH GraphQL API, I couldn't find how to dispatch events.
Is it even possible to trigger a workflow_dispatch event using the API?
Yes, it's possible, manually or through the Github API.
Manually (through the Actions tab on your repository.)
Here is an official documentation about it
Basically, once you select the workflow on the tab, if the workflow implementation has the workflow_dispatch trigger, the option Run workflow will appear on the right part of the window, like this:
With the Github API
On the official Github Documentation, there is a service to create a workflow dispatch event
Here is a curl example:
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/octocat/hello-world/actions/workflows/42/dispatches \
-d '{"ref":"main"}'
Note that you can also send workflow inputs through this API as well.
You can also find more references about this in this article.
There is also another Github API service to trigger repository_dispatch events.
Bonus
If you're looking for triggering those workflow_dispatch events (and repository_dispatch events) through a terminal command line, you can use this automation in Python. The implementation can be found in this class.
You can also trigger workflow_dispatch via the GH CLI tool: gh workflow run docs.
E.g.: gh workflow run <WORKFLOW_ID> -f param_1=foo
You can get workflow IDs via gh workflow list.
Or you can also use the workflow file name instead of the workflow ID.
E.g.: gh workflow run staging.yml -f param_1=foo
Here's an example of python code to trigger GitHub workflow.
You can get the workflow ID via gh workflow list, see: https://stackoverflow.com/a/71972073/1661491
github_token is the classic personal token, see: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
workflow_ref is the branch or tag.
import requests
import json
parameter_dict = ...
github_token = ...
workflow_ref = ...
workflow_id = ...
org = ...
repo_name = ..
inputs_str = json.dumps(parameter_dict)
response = requests.post(
f"https://api.github.com/repos/{org}/{repo_name}/actions/workflows/{workflow_id}/dispatches",
headers={"Authorization": f"Bearer {github_token}"},
data=f'{{"ref": "{workflow_ref}", "inputs": {inputs_str}}}'
)
if response.status_code >= 400:
raise ValueError(f"Failed to trigger workflow: {response.status_code} {response.text}")
Workflow ID can also by the workflow file name
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/<USER>/<REPO>/actions/workflows/build.yaml/dispatches \
-d '{"ref":"main"}'
https://docs.github.com/en/rest/actions/workflows?apiVersion=2022-11-28#create-a-workflow-dispatch-event

Jenkins http plugin to upload file using rest

I am trying to upload a file to a rest server from jenkins using http plugin. I have a jenkins pipelie where a step involves loading a file(type formData)
to a server using rest.
the server side method uses two parameters:
(#FormDataParam("file") InputStream file, #FormDataParam("fileName") String fileName)
I am using the below method
def filename = "${WORKSPACE}/Test.txt"
data="""{ \"fileName\" : \"Test.txt\" }"""
resp3 = httpRequest consoleLogResponseBody: true,url: "http://<url>",contentType:'APPLICATION_OCTETSTREAM',customHeaders:[[name:'Authorization', value:"Basic ${auth}"]],httpMode: 'POST',multipartName: 'Test.txt',uploadFile: "${filename}",requestBody:data,validResponseCodes: '200'
but when I run the status code is 400 and in the server logs the message is that no filestream and no filename is received i.e not able to get both the arguments.
Please let me know where it is getting wrong
Regards
You can try using curl instead of built-in Jenkins methods:
curl -XPOST http://<url> -H 'Content-Type: application/octet-stream' -H 'Authorization: Basic ${auth}' --data-binary '{\"fileName\" : \"Test.txt\" }'
You can debug it first from within shell. Once it's working, wrap it in sh directive:
sh "curl ..."
Since I was running on windows so bat + curl worked for me .With this workaround I was able to transfer files using jenkins and rest
However using httpRequest from jenkins inbuild library is still not working.

jfrog cli artifact search by filename pattern

I want to search for a filename pattern across entire JFrog ARM
without knowing the explicit repository name in the JFrog cli.
jfrog rt s "reponame/*pattern*"
is giving the results as expected in a specific repo.
But I have repo1, repo2, repo3, ... so on.
How do I search using wildcard for reponame, below is not working.
jfrog rt s "*/*pattern*"
Basically I want the jfrog cli equlivalent of the curl GET request search
"https://server/artifactory/api/search/artifact?name=*pattern*"
This is not for cli client, but an alternative way to get desired feature. Spent some time looking at API here:
https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API
I recommend to scroll down that page slowly and read in entirety as a lof of possible commands, syntax is excellent, I executed a few searches and they searched all local repositories. No need to recursively search 1 by 1. Command syntax:
export url="http://url/to/articatory"
curl --noproxy '*' -x GET "$url/api/search/artifact?name=log4j*"
Read link above for more granular search options/syntax.
How I set it up:
alias artpost='curl -X POST "http://url/artifactory/api/search/aql" -T - -u admin:password'
Some example usage:
echo 'items.find({"name": {"$match" : "log4j*"}})' | artpost
echo 'items.find({"$and" : [{"created" : {"$gt" : "2017-06-12"}},{"name": {"$nmatch" : "*surefire*"}}]})' | artpost

How to pass variables to Buildbot?

I'm using Buildbot V.0.9.0rc3
My Buildbot triggers when I send a change via command line or if I receieve an http Post request to the correct address.
Currently I'm sending changes to Buildbot in two different ways:
$ buildbot sendchange -m localhost:9999 -a example-user:pass -W me -C default
or
curl -X POST -d author=aalvz -d comments=mycomment -d project=my_project -d category=default -d repository=some http://192.168.33.20:8020/change_hook/base
My schedulers are defined like this:
c['schedulers'].append(schedulers.SingleBranchScheduler(
name="waiter",
builderNames=["runtests"],
change_filter=util.ChangeFilter(category='default')))
c['www'] = dict(port=8020,
plugins=dict(waterfall_view={}, console_view={}),
change_hook_dialects={
'base': True,
'somehook': {'option1':True,
'option2':False}})
And my Step in factory cloning a repo looks like this:
factory.addStep(steps.Git(repourl='git#github.com:AAlvz/my_repo.git', mode='full', workdir='newFolder', branch='my_branch', submodules=True, clobberOnFailure=True))
I would like to receive a POST with some data and use that data to trigger different commands. Something like: (using $ to make the variables noticeable)
factory.addStep(steps.Git(repourl=$myjson.name, mode='full', workdir=$myjson.path, branch=$myjson.branch, submodules=True, clobberOnFailure=True))
That way I could send a JSON like:
{myjson: {name: github/myrepo.git, path: /tmp/my/path, branch: my_branch}}
and be able to clone the repository provided by the JSON.
Thanks in advance! I hope the question is clear enough. I can provide with logs or any needed configuration. Thanks!
This is solved Using Buildbot Properties.
You cand send them via command line (with PBChangeSource) using the flag
buildbot sendchange ... --properties=my_property:myvalue
The flag can be used multiple timpes if multiple properties are needed.

GitHub api to obtain last N number of commits

Is it possible to obtain last N number of commits to a particular branch in a GitHub repository using GitHub API ?
I just found few GitHub api details regarding the commits here, but none of them are giving details about last N number of commits!
Anyone can provide a better idea about this ?
Also, Is it possible to identify the changed file type during the last commit from a user ?
You can try this Github API to get the last N number of commits,
INPUT:
GIT_REPO="https://api.github.com/repos/kubernetes/kubernetes" # Input Git Repo
BRANCH_NAME="master" # Input Branch Name
COMMITS_NUM="5" # Input to get last "N" number of commits
curl --silent --insecure --request GET --header "Accept: application/vnd.github.inertia-preview+json" "$GIT_REPO/commits?sha=$BRANCH_NAME&page=1&per_page=1000" | jq --raw-output '.[] | "\(.sha)|\(.commit.author.date)|\(.commit.message)|\(.commit.author.name)|\(.commit.author.email)" | gsub("[\n\t]"; "")' | awk 'NF' | awk '{$1=$1;print}' | head -$COMMITS_NUM
OUTPUT:
COMMIT_ID|DATE/TIME|COMMIT_MESSAGE|AUTHOR_NAME|AUTHOR_EMAIL
5ed4b76a03b5eddc62939a1569b61532b4a06a72|2020-11-26T15:24:19Z|Merge pull request #96421 from dgrisonnet/fix-apiservice-availabilityFix aggregator_unavailable_apiservice gauge|Kubernetes Prow Robot|k8s-ci-robot#users.noreply.github.com
c1f36fa6f28d3618c03b65799bc3f58007624e5f|2020-11-25T06:32:41Z|Merge pull request #96829 from songjiaxun/azuredisk_api_versionfix: change disk client API version for Azure Stack|Kubernetes Prow Robot|k8s-ci-robot#users.noreply.github.com
c678434623be4957d892a9865e5649f887a40c49|2020-11-24T21:20:39Z|Merge pull request #96831 from bobbypage/vendor-cadvisor-v0_38_5vendor: update cAdvisor to v0.38.5|Kubernetes Prow Robot|k8s-ci-robot#users.noreply.github.com
c652ffbe4a29143623a1aaec39f745575f7e43ad|2020-11-24T14:59:01Z|Merge pull request #96636 from Nordix/disable-nodeport-2service.spec.AllocateLoadBalancerNodePorts followup|Kubernetes Prow Robot|k8s-ci-robot#users.noreply.github.com
4a46efb70701ee00028723ecb137e401d83be4f4|2020-11-24T07:45:19Z|vendor: update cAdvisor to v0.38.5|David Porter|david#porter.me
Note:
1.Make sure you have installed jq to get output in the desired format and parse json key as per your requirement.
2.Make sure to update the Git Repo Url in "curl" command.