gitlab-ci.yaml: 获取变更的文件目录

需求

在gitlab-ci.yaml文件中获取变更文件的目录,获取目录名后做其他操作,比如在不同目录docker build

原理

根据 git diff 命令的输出,用 linux 命令做处理, 例如下命令

➜ git diff --name-only | awk -F/ '{print $1}' | sort -u        
.gitlab-ci.yml
Dockerfile
README.md
ansible
jenkinks_pipeline.groovy
scripts
spike_hour
wohle_hour_one_day

可以看到上述结果是,获取的包括文件名称和目录名,需要在借助shell脚本,分辨出目录

    if [ ! -d scripts ]; then
        continue
      fi

实现

节选自 gitlb-ci.yaml

build_docker_image:
  stage: dockerise
  tags:
   - delv-docker 
  image: docker
  services:
    - docker:dind
  variables:
    REPOSITORY_URL: *
    KUBERNETES_SERVICE_ACCOUNT: gitlab-runner
    DOCKER_HOST: tcp://localhost:2375
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  script:
    - >
    git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME;
# git diff 循环整个输出
    for dir in $(git diff --name-only $CI_COMMIT_SHA origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME | awk -F/ '{print $1}' | sort -u); do
     #  判断是否是文件目录类型`dictionary`,
      if [ ! -d $dir ]; then
        #如果不是 则跳过剩下的步骤
        continue
      fi
     # 是 `dictionary` 则进入
      cd $dir
      if [ ! -f Dockerfile ]; then
        echo "WARN: no Dockerfile in directory $dir, skipping"
        continue
      fi
      export APP_NAME_BUILD=$(echo $dir| sed "s/\//_/g" | sed "s/-/_/g")
      export VERSION=${CI_JOB_ID}_$(echo $CI_COMMIT_SHA | head -c 8)
      docker build -t $REPOSITORY_URL:$APP_NAME_BUILD-$VERSION .
      docker push $REPOSITORY_URL:$APP_NAME_BUILD-$VERSION
      echo "#########################################################################"
      echo "# Pushed Docker Image: $REPOSITORY_URL:$APP_NAME_BUILD-$VERSION"
      echo "#########################################################################"
    done
  only:
    refs:
      - master
    changes:
      - Dockerfile
      - scripts/*
      - .gitlab-ci.yml

你可能感兴趣的:(gitlab-ci.yaml: 获取变更的文件目录)