访问文件中的变量特定键,gitlab-ci

huangapple go评论61阅读模式
英文:

how to access specific key in Variables from file, gitlab-ci

问题

我想在Git中的一个文件夹中存储一个名为.env的文件,其内容如下:

a=香蕉
b=苹果

在我的流水线部署阶段中,我想包括这个文件并将其导出到环境变量,以便我的Docker容器可以接收它并将适当的值设置到docker-compose中。

我尝试了以下方法,但似乎没有成功:

部署生产环境:

  阶段: 部署

  镜像: 我的镜像

  变量:
    包括: /pr/.env

  脚本:
      - cat $a
      - echo $a
      - cat $b
      - echo $b
      - export .env

在GitLab CI中是否可能实现这个功能?

英文:

I would like to have a file in store in a folder in git named .env with the following content:

a=bananas
b=apples

in my pipeline deployment stage, I would like to include this file and export it to the env variables, so that my docker container would receive it and set the proper values into docker-compose.

I tried without much lucky the following:

Deploy Production:

  stage: deploy

  image: my_image
  variables:
    include: /pr/.env
  script:
      - cat $a
      - echo $a
      - cat $b
      - echo $b
      - export .env

it doesn't seem to work, is it possible in gitlab-ci?

答案1

得分: 2

以下是您要翻译的部分:

在部署阶段的(shell)脚本中,您可以直接在导出变量时使用文件作为源:

部署生产:
  阶段:部署
  镜像:我的镜像
  脚本:
      - set -o allexport; source .env; set +o allexport
      - echo $a
      - echo $b

如果您确实需要Gitlab解释变量,您可以使用带有dotenv artifacts的动态变量:

生成dotenv artifact:
  阶段:.pre
  脚本:
    - echo "生成变量" ## 实际上这里需要脚本,但实际上没有什么可做的
  构件:
    报告:
      dotenv:.env

部署生产:
  阶段:部署
  镜像:我的镜像
  脚本:
      - echo $a
      - echo $b

希望这对您有所帮助。

英文:

You can directly [source your file while exporting variables][2] in your (shell) script of the deploy stage:

Deploy Production:
  stage: deploy
  image: my_image
  script:
      - set -o allexport; source .env; set +o allexport
      - echo $a
      - echo $b

[2]: https://stackoverflow.com/a/30969768/13934411 "Answer to: Set environment variables from file of key/value pairs"

If you really need variables to be interpreted by Gitlab, you can use dynamic variables with dotenv artifacts:

Generate dotenv artifact:
  stage: .pre
  script: 
    - echo "generating variables" ## script is needed but in fact there is nothing to do here
  artifacts:
    reports:
      dotenv: .env

Deploy Production:
  stage: deploy
  image: my_image
  script:
      - echo $a
      - echo $b

huangapple
  • 本文由 发表于 2023年6月8日 19:15:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定