Quiero ejecutar un script de python para establecer algunas variables de entorno en las acciones de GitHub. Quiero usar esas variables de entorno más adelante en mis pasos de acciones de GitHub. Mi secuencia de comandos de python se parece a:
new_ver = get_version_from_commit(commit_msg) if new_ver: if new_ver == "false": os.environ["SHOULD_PUSH"] = "0" print("Not pushing the image to k8s") exit(0) else: new_tag = app_name + ":" + str(new_ver) os.environ["DOCKER_IMAGE_TAG"] = new_tag os.environ["SHOULD_PUSH"] = "1" print("New tag: " + new_tag) exit(0)Parte de mi archivo de acciones de GitHub, después de la ejecución del script de python anterior se ve así:
- name: Print env var run: echo ${{ env.DOCKER_IMAGE_TAG }} - name: Build and push id: docker_build uses: docker/build-push-action@v2 with: push: true tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE_TAG }}Pero usar os.environ no expondrá la variable de entorno fuera del proceso de python. Cómo puedo arreglar esto ?
No puede establecer variables de entorno directamente. En su lugar, debe escribir sus variables de entorno en un archivo, cuyo nombre puede obtener a través $GITHUB_ENV .
En un simple paso de flujo de trabajo, puede agregarlo al archivo así (de los documentos ):
echo "{name}={value}" >> $GITHUB_ENVEn python, puedes hacerlo así:
import os env_file = os.getenv('GITHUB_ENV') with open(env_file, "a") as myfile: myfile.write("MY_VAR=MY_VALUE")Dado este script de python, puede configurar y usar su nueva variable de entorno de la siguiente manera:
- run: python write-env.py - run: echo ${{ env.MY_VAR }}Me pregunté cómo configurar dos o más variables de entorno. Tienes que separar estas variables con un salto de línea. Aquí hay un ejemplo:
import os env_file = os.getenv('GITHUB_ENV') with open(env_file, "a") as myfile: myfile.write("MY_VAR1=MY_VALUE1\n") myfile.write("MY_VAR2=MY_VALUE2")