GitLab CI腳本編寫

1、GitLab CI腳本基本語法

GitLab CI Runner常用的有兩種,一種是Shell的,另一種是Docker的,採用Docker Runner的話需要指定具體鏡像,腳本中可以通過tags指定執行該作業的Runner

基本語法案例

image: xxx # 基礎鏡像,如果使用docker runner但是沒有指定鏡像時默認採用此鏡像

before_script: # 定義在每個作業的腳本之前運行的命令
  - xxx

after_script: # 定義在每個作業的腳本之後運行的命令
  - xxx

stages: # 定義作業可以使用的階段,如果任何一步作業失敗,則不會執行下一步的作業
  - build
  - test
  - deploy

build: # 工作
  stage: build # build階段
  tags: # 指定運行該腳本的Runner
    - dev-build
  only: # 定義作業將要運行的分支和標籤的名稱
    - tags # 打tag時纔會執行
    - web # 只有在web界面進行操作纔會執行
  script: # 由Runner執行的shell腳本
    - build_image

2、使用GitLab CI+jib實現自動打包鏡像

pom.xml中jib相關配置

            <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>jib-maven-plugin</artifactId>
                <version>1.6.1</version>
                <configuration>
                    <from>
                        <image>${base_image}</image>
                    </from>
                    <to>
                        <image>${registry_url}/${registry_project}/${project.artifactId}:${image_tag}</image>
                        <auth>
                            <username>${registry_username}</username>
                            <password>${registry_password}</password>
                        </auth>
                    </to>
                    <allowInsecureRegistries>true</allowInsecureRegistries>
                    <container>
                        <jvmFlags>
                            <jvmFlag>-Djava.security.edg=file:/dev/./urandom</jvmFlag>
                        </jvmFlags>
                        <user>app:app</user>
                    </container>
                </configuration>
            </plugin>

.gitlab-ci.yml文件

stages:
  - build

build:
  stage: build
  tags:
    - dev-build
  only:
    - tags
    - web
  script:
    - build_image

.auto_devops: &auto_devops |

  function build_image(){
      mvn compile jib:build \
      -Dbase_image=基礎鏡像地址 \
      -Dregistry_url=鏡像倉庫地址 \
      -Dregistry_project=鏡像倉庫中的項目名 \
      -Dregistry_username=用戶名 \
      -Dregistry_password=密碼 \
      -Dimage_tag=$CI_COMMIT_REF_NAME 
  }

before_script:
  - *auto_devops

build使用的Runner爲Shell Runner,$CI_COMMIT_REF_NAME可以得到在Gitlab打tag時指定的tag,最終實現的效果就是通過在GitLab上打tag使用jib自動打包鏡像

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章