🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Test and deploy a Ruby application with GitLab CI/CD > 原文:[https://docs.gitlab.com/ee/ci/examples/test-and-deploy-ruby-application-to-heroku.html](https://docs.gitlab.com/ee/ci/examples/test-and-deploy-ruby-application-to-heroku.html) * [Configure the project](#configure-the-project) * [Store API keys](#store-api-keys) * [Create Heroku application](#create-heroku-application) * [Create Runner](#create-runner) # Test and deploy a Ruby application with GitLab CI/CD[](#test-and-deploy-a-ruby-application-with-gitlab-cicd "Permalink") 该示例将指导您如何在 Ruby on Rails 应用程序中运行测试,以及如何将其自动部署为 Heroku 应用程序. 您还可以查看或派生完整的[示例源,](https://gitlab.com/ayufan/ruby-getting-started)并查看其过去[CI 作业](https://gitlab.com/ayufan/ruby-getting-started/-/jobs?scope=finished)的日志. ## Configure the project[](#configure-the-project "Permalink") 这是此项目的`.gitlab-ci.yml`文件的外观: ``` test: stage: test script: - apt-get update -qy - apt-get install -y nodejs - bundle install --path /cache - bundle exec rake db:create RAILS_ENV=test - bundle exec rake test staging: stage: deploy script: - gem install dpl - dpl --provider=heroku --app=gitlab-ci-ruby-test-staging --api-key=$HEROKU_STAGING_API_KEY only: - master production: stage: deploy script: - gem install dpl - dpl --provider=heroku --app=gitlab-ci-ruby-test-prod --api-key=$HEROKU_PRODUCTION_API_KEY only: - tags ``` 这个项目有三个工作: * `test` -用于测试 Rails 应用程序. * `staging` -用于每次推送到`master`分支时自动部署登台环境. * `production` -用于为每个创建的标签自动部署生产环境. ## Store API keys[](#store-api-keys "Permalink") 您需要在项目的**设置> CI / CD>环境变量中**创建两个**变量** : * `HEROKU_STAGING_API_KEY` -Heroku API 密钥,用于部署登台应用程序. * `HEROKU_PRODUCTION_API_KEY` -Heroku API 密钥,用于部署生产应用程序. Find your Heroku API key in [Manage Account](https://dashboard.heroku.com/account). ## Create Heroku application[](#create-heroku-application "Permalink") 对于每个环境,您都需要创建一个新的 Heroku 应用程序. 您可以通过[Heroku 仪表板](https://dashboard.heroku.com/)执行此操作. ## Create Runner[](#create-runner "Permalink") 首先安装[Docker Engine](https://s0docs0docker0com.icopy.site/installation/) . 要构建此项目,您还需要安装[GitLab Runner](https://docs.gitlab.com/runner/) . 您可以使用`gitlab.com`上的公共跑步者或注册自己的跑步者. 首先创建模板配置文件以通过复杂的配置: ``` cat > /tmp/test-config.template.toml << EOF [[runners]] [runners.docker] [[runners.docker.services]] name = "postgres:latest" EOF ``` 最后,注册运行器,并传递新创建的模板配置文件: ``` gitlab-runner register \ --non-interactive \ --url "https://gitlab.com/" \ --registration-token "PROJECT_REGISTRATION_TOKEN" \ --description "ruby:2.6" \ --executor "docker" \ --template-config /tmp/test-config.template.toml \ --docker-image ruby:2.6 ``` 使用上面的命令,您将创建一个使用[`ruby:2.6`](https://hub.docker.com/_/ruby)图像并使用[PostgreSQL](https://hub.docker.com/_/postgres)数据库的 Runner. 要访问 PostgreSQL 数据库,请以没有密码的用户`postgres`身份连接到`host: postgres` .