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。
wget https://dl.min.io/server/minio/release/linux-amd64/minio
chmod +x minio
mv minio /usr/local/bin/minio
minio -v
minio version RELEASE.2022-02-26T02-54-46Z
wget https://dl.min.io/client/mc/release/linux-amd64/mc
chmod +x mc
mv mc /usr/local/bin/mc
mc -v
mc version RELEASE.2022-02-26T03-58-31Z
mkdir -p /opt/minio/data
mkdir -p /opt/minio/logs
#!/bin/bash
export MINIO_ROOT_USER=minio
export MINIO_ROOT_PASSWORD=minio123456
nohup minio server /opt/minio/data > /opt/minio/logs/minio.log 2>&1 &
mc alias set myminio http://10.10.10.60:9000 minio minio123456
默认对外服务端口 9000
mc alias set myminio http://10.10.10.60:9000 minio minio123456
mc mb myminio/gitlab-cache
config.toml 增加以下 cache 配置:
concurrent = 10
check_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 生效。
.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
.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
.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/*