task icon indicating copy to clipboard operation
task copied to clipboard

Feature: Dynamically added env variables

Open michaszcz opened this issue 1 year ago • 2 comments

I'd like to have some option to set env variables dynamically for all steps of the task.

Example 1:

version: '3'

tasks:
  greet:
    cmds:
      - export GREETING=Hello
      - echo $GREETING  # Currently it'll print an empty string, I'd like to receive the value `Hello`

Example 2:

version: '3'

tasks:
  task_name:
    dynamic_env:  # Currently not possible
      sh: python script_that_exports_env_variables.py
    cmds:
      - echo $DYNAMIC_VAR1 $DYNAMIC_VAR2  # Env vars set by the script

Without the feature I have to export variables and use them in one step - example: Example 2:

version: '3'

tasks:
  task_name:
    cmds:
      - ./export_vars.sh && echo $DYNAMIC_VAR1 $DYNAMIC_VAR2
      - echo $DYNAMIC_VAR1 $DYNAMIC_VAR2  # Currently vars are not available in this step

michaszcz avatar Sep 04 '24 21:09 michaszcz

This is possible to set dynamic env variable but only one at the same time :

version: '3'

tasks:
  greet:
    env:
      GREETING: {sh: echo 'hello'}
      FOO: bar
    cmds:
      - echo $GREETING

If you want to add multiple env variable at the same time, I would use dotenv files and follow this issue : https://github.com/go-task/task/issues/1381

vmaerten avatar Sep 21 '24 16:09 vmaerten

Even if dotenv were available, it would still have a few issues:

  1. It would require generating a dotenv file and removing it after task execution, which could cause issues in parallel execution.
  2. Environment variables must remain the same throughout the task's execution.

michaszcz avatar Sep 24 '24 13:09 michaszcz

+1

My use case is that I'd like to dynamically define $A or $B from a script depending on what's available in the environment. I implemented this logic as well as a bunch of other checks as an internal task and exported the appropriate variable for use in subsequent commands. Obviously, this didn't end up working as exported variables aren't visible to other commands. It would be nice to be able to affect the 'global task environment' in some way from within tasks. There are other methods to achieve what I'm doing, but they subvert Task's features rather than synergize with them.

Another use case: exporting environment variables from Task into the shell environment. Running export FOO=bar in the shell will make FOO available to other commands. Creating a task that does the same thing will have no effect. This matters in cases where you might want to simplify configuring your shell for some task or another (eg. setting the AWS_PROFILE to dev/prod, or exporting session tokens into the environment).

I think there's a lot of value in Task's sandboxing of environment variables, but it would be nice to have an escape hatch. Maybe something a la Github Action's echo "FOO=bar" >> $GITHUB_OUTPUT pattern.

Madgvox avatar Jan 26 '25 05:01 Madgvox