我想使变量可用于所有Node部署作业,以使Gitlab管道干燥,但我还想提供依赖于每个单独作业的其他变量。当我处理需要唯一环境变量的多个Node服务时,这将有所帮助。
在阅读文档时,似乎可以通过两种方式在.gitlab-ci.yml
文件中执行此操作:
在YAML锚定定义中包括全局变量,希望它将与特定于工作的var合并:
# anchor: global Node image deployment job
.deploy_node_image: &deploy_node_image
image: docker:latest
stage: deploy
services:
- docker:dind
variables: # global variables
REGION: "region"
ACCOUNT_ID: "id"
CLUSTER_NAME: "cluster"
script:
- apk add py-pip
- pip install awscli
- echo $CLUSTER_NAME $REGION $IMAGE_NAME $ACCOUNT_ID $SERVICE_NAME $SERVICE_DIR
- aws ecr get-login-password --region $REGION | docker login --username AWS
--password-stdin https://$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com
- cd $CI_PROJECT_DIR/ingenio/new-backend/$SERVICE_DIR
- docker build
-t $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$IMAGE_NAME:latest .
- docker push
$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$IMAGE_NAME:latest
- aws ecs update-service
--region $REGION
--cluster $CLUSTER_NAME
--service $SERVICE_NAME
# specific job
deploy:users-service:
<<: *deploy_node_image
variables:
IMAGE_NAME: "users-api"
SERVICE_NAME: "serviceName"
SERVICE_DIR: "/endpoint"
定义一组全局变量并将其与作业特定的变量合并:
node_variables: &node_globals
variables:
REGION: "region"
ACCOUNT_ID: "id"
CLUSTER_NAME: "cluster"
# anchor: global Node image deployment job
.deploy_node_image: &deploy_node_image
image: docker:latest
stage: deploy
services:
- docker:dind
script:
- apk add py-pip
- pip install awscli
- echo $CLUSTER_NAME $REGION $IMAGE_NAME $ACCOUNT_ID $SERVICE_NAME $SERVICE_DIR
- aws ecr get-login-password --region $REGION | docker login --username AWS
--password-stdin https://$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com
- cd $CI_PROJECT_DIR/ingenio/new-backend/$SERVICE_DIR
- docker build
-t $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$IMAGE_NAME:latest .
- docker push
$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$IMAGE_NAME:latest
- aws ecs update-service
--region $REGION
--cluster $CLUSTER_NAME
--service $SERVICE_NAME
# specific job
deploy:users-service:
<<: *deploy_node_image
variables:
<<: *node_globals
IMAGE_NAME: "users-api"
SERVICE_NAME: "serviceName"
SERVICE_DIR: "/endpoint"
两者均无效,并且第一个AWS ECR命令失败,因为$REGION
为null,以及方法1中的log语句中方法1的节点锚点和方法2中的全局变量包括的所有变量。节点锚点。在日志中只能看到实际作业中包含的var,这让我认为它只是覆盖。
那我怎么合并它们?
答案 0 :(得分:1)
当您使用锚点或继承(使用extends
)合并两个作业时,“子”作业将覆盖父项的任何部分。这些部分本身不会合并。因此,父variables
部分基本上被子variables
部分覆盖和忽略。扩展机制是YAML标准的一部分,与GitLab无关。
variables
部分仅创建环境变量,因此您可以在before_script
部分中执行相同的操作,如下所示:
# Note: these are global variables. You don't need to add them to an anchor.
variables:
REGION: "region"
ACCOUNT_ID: "id"
CLUSTER_NAME: "cluster"
.deploy_node_image:
image: docker:latest
stage: deploy
# You can define the "global" variables section here INSTEAD if you want.
script:
- echo $REGION
- echo $IMAGE_NAME
deploy:users-service:
<<: *deploy_node_image
before_script:
- export IMAGE_NAME="users-api"
- export SERVICE_NAME="serviceName"
- export SERVICE_DIR="/endpoint"
有关更多信息,请参见GitLab environment variables。