Add github run number to a file in github repo

Viewed 91

I am trying to add the github run number to a file in the github repository. The file looks like the following:

import json
from importlib import reload
import hashlib
from logging import raiseExceptions
import os
import importlib

qwe = importlib.import_module("asd-64")

The 64 signifies the github run number. I have tried doing the following:

qwe = importlib.import_module("asd-${{ github.run_number }}")

This doesn't work and prints the string ${{ github.run_number }}. Is there a way to achieve this?

1 Answers

I've done it using a python script and placeholders. (It might not be the best solution, but at least it works!)

The file to update would look like this:

test.py

import json
from importlib import reload
import hashlib
from logging import raiseExceptions
import os
import importlib

#placeholder1

The script to update it would look like this:

update_file.py

import os
import re

print("START")

WORKSPACE = os.getenv("WORKSPACE")
GITHUB_RUN_NUMBER = os.getenv("GITHUB_RUN_NUMBER")

FILE = f"{WORKSPACE}/test.py"

with open(FILE, "r") as file:
    content = file.read()

importlib = f'qwe = importlib.import_module("asd-{GITHUB_RUN_NUMBER}")'

content = re.sub(r"#placeholder1", importlib, content)

with open(FILE, "w") as file:
    file.write(content)

print("END")

And the workflow file that would perform the operation would look like this:

workflow.yml

name: ...

on:
  workflow_dispatch:

jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2.3.4

      - uses: actions/setup-python@v4
        with:
          python-version: 3.8

      - name: Execute Python script to update test.py file
        run: python .github/scripts/update_file.py
        env:
          WORKSPACE: ${{ github.workspace }}
          GITHUB_RUN_NUMBER: ${{ github.run_number }}

      - run: cat test.py

Here is the related and successful workflow run.

(workflow file, update_file.py file, test.py file)

Related