本文来自:
李发富 极狐(GitLab) 高级技术支持工程师
A:CI/CD 执行好慢呐,每个 Job 执行的时候都得去下载外部依赖,好烦!
B: 这你就自寻烦恼了吧,其实可以用 cache 来避免这种状况。
A:cache?何方神圣?怎么用?快来拯救我!
B :cache 的使用很简单,follow me💁♀️
极狐 GitLab CI/CD Job 在运行过程中不可避免的要下载一些外部依赖,cache 的存在是为了让不同 Job 之间能够共享这些文件,避免每个 Job 都去再次下载,这样做能够节约 CI/CD 的执行时间,提升 CI/CD 的执行效率。
本文以兼容 s3 标准的 minio 为例,向大家演示如何使用 cache。
安装 minio
下载 minio server
wget https://dl.min.io/server/minio/release/linux-amd64/miniochmod +x miniomv minio /usr/local/bin/miniominio -v
minio version RELEASE.2022-02-26T02-54-46Z
复制代码
下载 minio client
wget https://dl.min.io/client/mc/release/linux-amd64/mcchmod +x mcmv mc /usr/local/bin/mcmc -v
mc version RELEASE.2022-02-26T03-58-31Z
复制代码
配置 minio 数据目录
mkdir -p /opt/minio/datamkdir -p /opt/minio/logs
复制代码
创建 start_minio_server.sh 启动脚本
#!/bin/bashexport MINIO_ROOT_USER=minioexport MINIO_ROOT_PASSWORD=minio123456nohup minio server /opt/minio/data > /opt/minio/logs/minio.log 2>&1 &
复制代码
启动 minio server
chmod +x start_minio_server.sh./start_minio_server.sh
复制代码
(默认对外服务端口 9000)
为客户端设置别名
mc alias set myminio http://10.10.10.60:9000 minio minio123456
复制代码
配置存储桶
mc mb myminio/gitlab-cache
复制代码
配置 runner
config.toml 增加以下 cache 配置:
concurrent = 10check_interval = 0
[session_server] session_timeout = 1800
[[runners]] name = "docker runner" url = "https://gitlab.leffss.cn" token = "xdfVPzdySQQNPCVgBxK1" executor = "docker" [runners.cache] type = "s3" Shared = true [runners.cache.s3] ServerAddress = "10.10.10.60:9000" AccessKey = "minio" SecretKey = "minio123456" BucketName = "gitlab-cache" Insecure = true
复制代码
重启 runner 生效。
使用 cache 示例
python
.gitlab-ci.yml 参考:
image: python:3.9.7
stages: - test
variables: PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" cache: paths: - .cache/pip/ # 已项目 id 区分 cache,如果不区分,就是全局 cache key: $CI_PROJECT_ID
job1: stage: test script: - pip install ansible==2.9.2
复制代码
or
image: python:3.9.7
stages: - test
cache: paths: - pip-cache # 已项目 id 区分 cache,如果不区分,就是全局 cache key: $CI_PROJECT_ID
before_script: - export PIP_CACHE_DIR="pip-cache" - mkdir -p pip-cache
job1: stage: test script: - pip install ansible==2.9.2
复制代码
nodejs
.gitlab-ci.yml 参考:
variables: NPM_CONFIG_CACHE: npm_cache NPM_CONFIG_REGISTRY: https://registry.npm.taobao.org
default: cache: paths: - ${NPM_CONFIG_CACHE}
build: stage: build image: node:14-alpine script: - node -v - npm -v - npm ci - npm run build artifacts: name: "build-package" paths: - dist expire_in: 1 day
复制代码
java maven
.gitlab-ci.yml 参考:
build: image: maven:3.8.5-jdk-11 stage: build variables: MAVEN_CLI_OPTS: "-s .m2/settings.xml --batch-mode" MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository" cache: paths: - .m2/repository/ - target/ key: $CI_PROJECT_ID script: - mvn package - ls -l target/*
复制代码
评论