Gasim
Gasim

Reputation: 7961

Gitlab CI how to run tests before building docker image

I have a Python based repository and I am trying to setup Gitlab CI to Build a Docker image using Dockerfile and pushing the image to Gitlab's Registry.

Before building and deploying the Docker image to registry, I want to run my unit tests using Python. Here is my current gitlab-ci.yml file that only does testing:

image: python:3.7-slim
before_script:
  - pip3 install -r requirements.txt

test:
  variables:
    DJANGO_SECRET_KEY: some-key-here
  script:
  - python manage.py test

build:
  DO NOT KNOW HOW TO DO IT

I am checking some templates from Gitlab's website and found one for Docker:

# This file is a template, and might need editing before it works on your project.
# Official docker image.
image: docker:latest

services:
  - docker:dind

before_script:
  - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY

build-master:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE" .
    - docker push "$CI_REGISTRY_IMAGE"
  only:
    - master

build:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"
  except:
    - master

However, both of these do not work for me because I need to have python for testing and docker for building the image. Is there way to do it with Gitlab CI without creating a custom Docker image that has both python and Docker installed?

Upvotes: 3

Views: 3323

Answers (1)

Gasim
Gasim

Reputation: 7961

I found out that I can create multiple jobs, each with their own images:

stages:
  - test
  - build

test:
  stage: test
  image: python:3.7-slim
  variables:
    DJANGO_SECRET_KEY: key
  before_script:
    - pip3 install -r requirements.txt
  script:
    - python manage.py test
  only:
    - master

build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE" .
    - docker push "$CI_REGISTRY_IMAGE"
  only:
    - master

Upvotes: 6

Related Questions