DRONE_STEP_NAME not available as substitution in environment

We’re trying to use DRONE_STEP_NAME to help populate our environment variables for a step:

steps:
  - name: step1
    image: "python:3.8-slim"
    environment:
      MYVAR: "DRONE_STEP_NAME=${DRONE_STEP_NAME}, DRONE_STEP_NUMBER=${DRONE_STEP_NUMBER}"
    commands:
      - env | egrep "MYVAR|STEP"       

When I look at my environment within the context of the step, MYVAR is not set correctly:

+ env | egrep "MYVAR|STEP"
DRONE_STEP_NUMBER=2
MYVAR=DRONE_STEP_NAME=, DRONE_STEP_NUMBER=
DRONE_STEP_NAME=step1

To provide some context, Drone emulates environment substitution and can replace ${var} in the yaml with a list of pre-defined variables (which includes most of the variables in this list). If the variable does not exist or is empty, it is replaced with an empty string. If you do not want a variable to be replaced, it can be escaped as $${var}. This behavior was inspired by docker-compose.

In your example yaml, you are attempting to expand the pipeline step name. The step name is not known until after the yaml is parsed. Since the emulated substitution occurs before the yaml is parsed, attempting to use this value would always result in blank substitution.

Instead of relying on emulated substitution, you can create the environment variable at runtime in your command sections. Just remember to escape the variables (as shown below) to ensure they are ignored by the emulated substitution.

steps:
  - name: step1
    image: "python:3.8-slim"
    commands:
      - export MYVAR=DRONE_STEP_NAME=$${DRONE_STEP_NAME}, DRONE_STEP_NUMBER=$${DRONE_STEP_NUMBER}"
      - env | egrep "MYVAR|STEP"  

Please see the environment Reference for a list of parameters that can be used for substitution. Only parameters in this list can be used for substitution.

There’s no mention anywhere (that I can find) that the DRONE_STEP_* variables are an exception to this. The fact that DRONE_STAGE_* variables are substituted implies parsing of the yaml has already happened to some extent … or you wouldn’t know which pipeline are available. So the behavior between the two are inconsistent.

And we can’t really use your workaround (which IMO is just a workaround) because we’re trying to build an environment variable to pass to the docker plugin. I used the python image just as an easy way to show the behavior.

I’d love to see the DRONE_STEP_* variables enabled for substitution but at the very least, the documentation should get fixed to make this behavior clear.

1 Like