Search code examples
pythongithub-actions

Github action to execute a Python script that create a file, then commit and push this file


My repo contains a main.py that generates a html map and save results in a csv. I want the action to:

  1. execute the python script (-> this seems to be ok)
  2. that the file generated would then be in the repo, hence having the file generated to be added, commited and pushed to the main branch to be available in the page associated with the repo.

name: refresh map

on:
  schedule:
    - cron: "30 11 * * *"    #runs at 11:30 UTC everyday

jobs:
  getdataandrefreshmap:
    runs-on: ubuntu-latest
    steps:
      - name: checkout repo content
        uses: actions/checkout@v3 # checkout the repository content to github runner.
      - name: setup python
        uses: actions/setup-python@v4
        with:
          python-version: 3.8 #install the python needed
      - name: Install dependencies
        run: |
          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
      - name: execute py script
        uses: actions/checkout@v3
        run: |
          python main.py
          git config user.name github-actions
          git config user.email [email protected]
          git add .
          git commit -m "crongenerated"
          git push

The github-action does not pass when I include the 2nd uses: actions/checkout@v3 and the git commands.

Thanks in advance for your help


Solution

  • If you want to run a script, then you don't need an additional checkout step for that. There is a difference between steps that use workflows and those that execute shell scripts directly. You can read more about it here.

    In your configuration file, you kind of mix the two in the last step. You don't need an additional checkout step because the repo from the first step is still checked out. So you can just use the following workflow:

    name: refresh map
    
    on:
      schedule:
        - cron: "30 11 * * *"    #runs at 11:30 UTC everyday
    
    jobs:
      getdataandrefreshmap:
        runs-on: ubuntu-latest
        steps:
          - name: checkout repo content
            uses: actions/checkout@v3 # checkout the repository content to github runner.
          - name: setup python
            uses: actions/setup-python@v4
            with:
              python-version: 3.8 #install the python needed
          - name: Install dependencies
            run: |
              if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
          - name: execute py script
            run: |
              python main.py
              git config user.name github-actions
              git config user.email [email protected]
              git add .
              git commit -m "crongenerated"
              git push
    
    

    I tested it with a dummy repo and everything worked.