Test and deploy a Python application with GitLab CI/CD
原文:https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html
Test and deploy a Python application with GitLab CI/CD
本示例将指导您如何在 Python 应用程序中运行测试,以及如何将其自动部署为 Heroku 应用程序.
您也可以查看或生成完整的示例源 .
Configure project
这是此项目的.gitlab-ci.yml文件的外观:
stages:
  - test
  - deploy
test:
  stage: test
  script:
    # this configures Django application to use attached postgres database that is run on `postgres` host
    - export DATABASE_URL=postgres://postgres:@postgres:5432/python-test-app
    - apt-get update -qy
    - apt-get install -y python-dev python-pip
    - pip install -r requirements.txt
    - python manage.py test
staging:
  stage: deploy
  script:
    - apt-get update -qy
    - apt-get install -y ruby-dev
    - gem install dpl
    - dpl --provider=heroku --app=gitlab-ci-python-test-staging --api-key=$HEROKU_STAGING_API_KEY
  only:
    - master
production:
  stage: deploy
  script:
    - apt-get update -qy
    - apt-get install -y ruby-dev
    - gem install dpl
    - dpl --provider=heroku --app=gitlab-ci-python-test-prod --api-key=$HEROKU_PRODUCTION_API_KEY
  only:
    - tags 
这个项目有三个工作:
test-用于测试 Django 应用程序.staging-用于每次推送到master分支时自动部署登台环境.production-用于为每个创建的标签自动部署生产环境.
Store API keys
您需要在 GitLab 项目的"设置">" CI / CD">"环境变量"中创建两个变量:
HEROKU_STAGING_API_KEY-Heroku API 密钥,用于部署登台应用程序.HEROKU_PRODUCTION_API_KEY-Heroku API 密钥,用于部署生产应用程序.
在" 管理帐户"中找到您的 Heroku API 密钥.
Create Heroku application
对于每个环境,您都需要创建一个新的 Heroku 应用程序. 您可以通过仪表板执行此操作.
Create Runner
首先安装Docker Engine .
要构建此项目,您还需要安装GitLab 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 "python-3.5" \
  --executor "docker" \
  --template-config /tmp/test-config.template.toml \
  --docker-image python:3.5 
使用上面的命令,您将创建一个使用python:3.5图像并使用PostgreSQL数据库的运行器.
要访问 PostgreSQL 数据库,请以没有密码的用户postgres身份连接到host: postgres .