Shahriar Zarir
Shahriar Zarir

Reputation: 127

Run github workflow with python

I have a python workflow in github here. I can run that workflow from the web interface. But problem is everytime I have to visit github and click on run workflow. Again I have to login in github from an unknown device to run that workflow. Is there any github module in python that can run a workflow using a personal access token? Or how can I run a workflow with github api using requests module? I searched about this topic on google but I didn’t found any solution that works. Many of those are out dated or not explained properly.

This is the workflow I used here:

name: Python
on:
  workflow_dispatch:
  
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: checkout repo
        uses: actions/[email protected]
      - name: Run a script
        run: python3 main.py
        

Upvotes: 3

Views: 3207

Answers (2)

nicolas.f.g
nicolas.f.g

Reputation: 1241

A more pythonic solution would be to use the pygithub package:

import github, os
g = github.Github(login_or_token=os.environ["GITHUB_PAT"])

repo = g.get_repo("my_org/my_repo")

workflow_name = "cicd.yml"
workflow = repo.get_workflow(workflow_name)

ref = repo.get_branch("develop")
workflow.create_dispatch(ref=ref)

See https://pygithub.readthedocs.io/en/latest/github_objects/Workflow.html

Upvotes: 0

Shahriar Zarir
Shahriar Zarir

Reputation: 127

Thanks to @C.Nivs & @larsks for helping me to find the right documentation. After experimenting with github api, finally I found my answer. Here is the code I used:

branch, owner, repo, workflow_name, ghp_token="main", "dev-zarir", "Python-Workflow", "python.yml", "ghp_..."

import requests

def run_workflow(branch, owner, repo, workflow_name, ghp_token):
    url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_name}/dispatches"
    
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {ghp_token}",
        "Content-Type": "application/json"
    }

    data = '{"ref":"'+branch+'"}'
    
    resp = requests.post(url, headers=headers, data=data)
    return resp
    
response=run_workflow(branch, owner, repo, workflow_name, ghp_token)

if response.status_code==204:
    print("Workflow Triggered!")
else:
    print("Something went wrong.")

Upvotes: 4

Related Questions