The documentation for AWS CodeBuild says (my emphasis):
Note
In buildspec version 0.1, CodeBuild runs each command in a separate instance of the default shell in the build environment. This means that each command runs in isolation from all other commands. Therefore, by default, you cannot run a single command that relies on the state of any previous commands (for example, changing directories or setting environment variables). To get around this limitation, we recommend that you use version 0.2, which solves this issue. If you must use buildspec version 0.1, we recommend the approaches in Shells and commands in build environments.
Based on the above, using buildspec version: 0.2
, I expect to be able to set an environment variable in one command, and have it persist into the next command.
However, this does not appear work as expected, at least when using powershell with the latest Windows Server Core 2019 image.
Here’s a minimal buildspec.yml
:
version: 0.2
env:
shell:
powershell.exe
phases:
install:
commands:
# show powershell version
- $PSversionTable
# single multiline command
- |
$env:FOO = "foo"
test-path env:FOO
# test persistence
- test-path env:FOO
And here’s the resulting output:
[Container] 2024/06/04 11:21:09.463805 Running command $PSversionTable
Name Value
---- -----
PSVersion 5.1.17763.5458
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.5458
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
[Container] 2024/06/04 11:21:10.022501 Running command $env:FOO = "foo"
test-path env:FOO
True
[Container] 2024/06/04 11:21:10.504454 Running command test-path env:FOO
False
Note the True
followed by False
for the tests in the output.
Also tried e.g. [System.Environment]::SetEnvironmentVariable
without any luck.
Am I doing something wrong?
Should I just use multiline commands everywhere, or use the workaround for buildspec version: 0.1
from the docs?
If you must use version 0.1, we recommend the following approaches:
- Include a shell script in your source code that contains the commands you want to run […]
- In your buildspec file or on the Build commands setting for the build phase only, enter a single command that includes all of the commands you want to run […]
Please note: I am aware that normal variables do persist, and I am aware of the env/variables
section, but I need to set environment variables dynamically in the install and/or build phases.
Related but do not answer the question:
- How to pass environment variable to the buildspec.yml for AWS codebuild
- …