gitlab-ci.yaml: 獲取變更的文件目錄

需求

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

原理

根據(jù) 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

可以看到上述結(jié)果是,獲取的包括文件名稱和目錄名,需要在借助shell腳本,分辨出目錄

    if [ ! -d scripts ]; then
        continue
      fi

實現(xiàn)

節(jié)選自 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 循環(huán)整個輸出
    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` 則進(jìn)入
      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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容