Passing dynamic environment variable to a secondary docker container

I’m attempting to pass an environment variable to a secondary docker container:

jobs:
    run_tests:
        docker:
            image: circleci/node:10.15
            environment:
              - DB_NAME: test_$CIRCLE_NODE_INDEX
            command: ["sh", "-c", "yarn start"]
        parallelism: 10

It seems like the environment variable doesn’t get interpolated. Is there any workaround for this?

Hi there! Could you share the whole config so we can see the context in which you are trying this? Please wrap it in 3 backticks so it formats correctly, such as

```
config here
```
1 Like

Is it alright now?

Yes, thank you. I’m not sure if this is possible, but try changing to this and see if it works?

- DB_NAME: test_{{ .Environment.CIRCLE_NODE_INDEX }}

It doesn’t work.
If I run env in the container I see DB_NAME=test_{{ .Environment.CIRCLE_NODE_INDEX }}
It seems like it’s interpreting it as a literal.

Drat. I was hoping. In that case, you are in need of this feature https://circleci.com/ideas/?idea=CCI-I-67

Please vote to show support and to track changes and feel free to comment to provide any clarity on your use case.

1 Like

Is that just a typo, or do you really not have a colon in your docker key here? I don’t think it will work like that. (If it is a typo, please always copy+paste your work).

1 Like

In the meantime, the OP could create their own child image of circleci/node:10.15 that accepts $CIRCLE_NODE_INDEX as a command parameter. Not quite as clean, admittedly, but I think it would work.

How would I pass the $CIRCLE_NODE_INDEX variable to my child image?

I guess you’d do something like this:

command: ["sh", "-c", "/your/custom/command", "--index", "$CIRCLE_NODE_INDEX"]

…though it occurs to me it depends on whether this part of the config allows environment variable injection. :grin:

I’ve tried that and the problem is the fact that the command executes inside my child container where the CIRCLE_NODE_INDEX variable doesn’t exist :cry:

Hmm, I would expect the command to be interpolated by CircleCI first. If your container receives the literal string "$CIRCLE_NODE_INDEX" then it means the env var outside of the container did not get injected in.

I did this:
command: ["sh", "-c", "echo DB_NAME=test_${CIRCLE_NODE_INDEX}; yarn start"]
When I check the logs in circle CI it looked like:
DB_NAME=test_
It seems like the variable was undefined.

Hmm, it’s hard to know what the problem is - either injection is supported at the host level and there is a problem passing it, or - as you say - a literal string is being injected (because interpolation is not supported in this part of the config file) and then it fails to look up inside the container.

The reference guide indicates that a string is acceptable for this key - maybe try that?

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.