pix*_*xel 9 environment-variables bitbucket-pipelines
我想在两个步骤中共享一个变量。
我将其定义为:
- export MY_VAR="FOO-$BITBUCKET_BUILD_NUMBER"
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在其他步骤中打印它时:
- echo $MY_VAR
Run Code Online (Sandbox Code Playgroud)
它是空的。
我如何共享这样的变量?
bel*_*cea 16
正如Mr-IDE和Rik Tytgat解释的那样,您可以通过将环境变量写入文件来导出环境变量,然后通过以下步骤将该文件作为工件共享。一种方法是在一个步骤中将变量写入 shell 脚本,将其定义为 an artifact,然后在下一步中将其作为源。
definitions:
steps:
- step: &build
name: Build
script:
- MY_VAR="FOO-$BITBUCKET_BUILD_NUMBER"
- echo $MY_VAR
- echo "export MY_VAR=$MY_VAR" >> set_env.sh
artifacts: # define the artifacts to be passed to each future step
- set_env.sh
- step: &deploy
name: Deploy
script:
# use the artifact from the previous step
- cat set_env.sh
- source set_env.sh
- echo $MY_VAR
pipelines:
branches:
master:
- step: *build
- step:
<<: *deploy
deployment: test
Run Code Online (Sandbox Code Playgroud)
注意:就我而言,set_env.sh作为工件发布的步骤并不总是我的管道的一部分。在这种情况下,请务必在下一步中检查该文件是否存在,然后再使用。
- step: &deploy
name: Deploy
image: alpine
script:
# check if env file exists
- if [ -e set_env.sh ]; then
- cat set_env.sh
- source set_env.sh
- fi
Run Code Online (Sandbox Code Playgroud)
akm*_*ith 10
我知道这个问题相当老了,但我找到了一种更干净的方法,无需跨步骤上传和下载工件。
您可以使用定义中的命令锚定脚本,EXPORT并将其显式重用为步骤的一部分,而不是定义锚定步骤。请注意,脚本锚中定义的脚本是单行脚本,需要&&多个命令。
definitions:
commonItems:
&setEnv export MY_VAR="FOO-$BITBUCKET_BUILD_NUMBER" &&
export MY_VAR_2="Hey" &&
export MY_VAR_3="What you're building"
Run Code Online (Sandbox Code Playgroud)
以下是您在步骤中的调用方式。
steps:
step:
- name: First step
script:
- *setEnv
- echo $MY_VAR # FOO-1
- echo $MY_VAR_2 # Hey
- echo $MY_VAR_3 # What you're building
- name: Second step
script:
- *setEnv
- echo $MY_VAR # FOO-1
- echo $MY_VAR_2 # Hey
- echo $MY_VAR_3 # What you're building
Run Code Online (Sandbox Code Playgroud)
您可以将所有环境变量复制到文件中,然后重新读取它们:
- step1:
# Export some variables
- export MY_VAR1="FOO1-$BITBUCKET_BUILD_NUMBER"
- export MY_VAR2="FOO2-$BITBUCKET_BUILD_NUMBER"
- echo $MY_VAR1
- echo $MY_VAR2
# Copy all the environment variables to a file, as KEY=VALUE, to share to other steps
- printenv > ENVIRONMENT_VARIABLES.txt
- step2:
# Read all the previous environment variables from the file, and export them again
- export $(cat ENVIRONMENT_VARIABLES.txt | xargs)
- echo $MY_VAR1
- echo $MY_VAR2
Run Code Online (Sandbox Code Playgroud)
注意:尽量避免使用其中包含空格或换行符的字符串(用于键或值)。该export命令将无法读取它们,并且可能引发错误。一种可能的解决方法是使用sed来自动删除其中包含空格字符的任何行:
# Copy all the environment variables to a file, as KEY=VALUE, to share to other steps
- printenv > ENVIRONMENT_VARIABLES.txt
# Remove lines that contain spaces, to avoid errors on re-import (then delete the temporary file)
- sed -i -e '/ /d' ENVIRONMENT_VARIABLES.txt ; find . -name "ENVIRONMENT_VARIABLES.txt-e" -type f -print0 | xargs -0 rm -f
Run Code Online (Sandbox Code Playgroud)
更多信息:
printenv命令恐怕,但是似乎不可能从一个步骤到另一个步骤共享环境变量,但是您可以在pipelines类别下的项目设置中为所有步骤定义全局环境变量。
Settings -> Pipelines -> Repository Variables
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2796 次 |
| 最近记录: |