如何在 Gitlab CI 中为 rails 项目使用缓存?

How to use cache for a rails project in Gitlab CI?

我一直在尝试在 rails 应用程序上为我的 ruby 利用 Gitlab Ci 的缓存,但到目前为止还没有成功,我的应用程序正在使用共享运行朋友们,也许这就是问题所在?

这是我的.gitlab-ci.yml

的内容
services:
  - postgres:latest

rspec:
  stage: test
  script:
    - apt-get update -qy
    - apt-get install -y nodejs
    - gem install bundler
    - bundle check --path vendor/bundle || bundle install --path vendor/bundle --jobs $(nproc)
    - cp config/database.gitlab-ci.yml config/database.yml
    - RAILS_ENV=test bundle exec rake db:create db:schema:load
    - bundle exec rspec
  cache:
    paths:
      - vendor/bundle
  tags:
    - ruby
    - postgres

当我测试 运行 时,我确实看到 运行ner 检查缓存的内容,但它从未恢复它:

gitlab-ci-multi-runner 1.1.3 (a470667)
Using Docker executor with image ruby:2.1 ...
Pulling docker image postgres:latest ...
Starting service postgres:latest ...
Waiting for services to be up and running...
Pulling docker image ruby:2.1 ...

Running on runner-8a2f473d-project-1129003-concurrent-0 via runner-8a2f473d-machine-1462982763-a9a70bd7-digital-ocean-4gb...
Cloning repository...
Cloning into '/builds/foo/bar'...
Checking out 30ea1b5f as master...
Note: checking out '30ea1b5f036808f7e27bfa32e939c1f591343ba6'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 30ea1b5... Fix width of tables contained in table-scroll divs
Checking cache for rspec/master...

$ apt-get update -qy

当构建即将完成时,我确实看到它正在尝试创建缓存:

Creating cache rspec/master...
vendor/bundle: found 8917 matching files

有什么想法吗?

Gitlab Runner 默认在 git 工作目录中创建缓存。正如您所提到的,您的缓存已正确创建,但它存储在 gitlab-运行ner 的当前 git 工作目录中。每当下一次构建是 运行 时,gitlab-运行ner 会清理工作目录(可能使用 git clean -dfx),这会删​​除 git 中的缓存目录工作目录。

您需要为 gitlab-运行ner 指定一个单独的缓存目录。您可以使用 cache_dir 设置键在 [[runners]] 部分的 /etc/gitlab-runner/config.toml 文件中手动指定。 Gitlab CI advanced configuration

您还可以在 gitlab 运行ner 注册期间使用 --cache-dir 选项指定缓存目录,如

gitlab-runner register --name blabblah --cache-dir /var/opt/gitlab/gitlab-runner-cache

希望对您有所帮助

缓存实际上在我发布这个问题几周后开始正常工作,不需要对我的配置进行任何更改。我相信这与 gitlab 推出的更新有关。