Search code examples
gitlab-ci

gitlab-ci: provide environment variable(s) to custom docker image in a pipeline


I want to set up a test stage for my gitlab-ci which depends on a custom docker image. I want to know how will I provide some config (like setting env variable to providing a .env file) to it so that the custom image runs properly and hence the stage. Current config:

test_job:
  only:
  refs:
    - master
    - merge_requests
    - web
stage: test
services:
  - mongo:4.0.4
  - redis:5.0.1
  - registry.gitlab.com/myteam/myprivaterepo:latest 
variables:
  - PORT=3000
  - SERVER_HOST=myprivaterepo
  - SERVER_PORT=9090
script: npm test

I want to provide environment variables to myprivaterepo docker image which connects to mongo:4.0.4 and redis:5.0.1 services for its functioning.

EDIT: The variables are MONGODB_URI="mongodb://mongo:27017/aics" and REDIS_CLIENT_HOST: "redis". These have no meaning for the app being tested but has meaning for the myprivaterepo image without which the test stage will fail.


Solution

  • I figured it out. It is as simple as adding the environment variables in the variables: part of the yaml. This is what worked for me:-

    test_job:
      only:
        refs:
          - master
          - merge_requests
          - web
    
        stage: test
    
        services:
          - mongo:4.0.4
          - redis:5.0.1
          - name: registry.gitlab.com/myteam/myprivaterepo:latest
            alias: myprivaterepo
    
        variables:
          - MYPRIVATEREPO_PORT: 9090 # Had to modify image to use this variable
          - MONGODB_URI: mongodb://mongo:27017/aics
          - REDIS_CLIENT_HOST: redis
          - PORT: 3000 # for app being tested
          - SERVER_HOST: myprivaterepo
          - SERVER_PORT: 9090
    
        script: npm test
    

    These variables seeem to be applied to all services.

    NOTE: There is a catch - you cannot use 2 images using same environment variable names.

    Like, I initially used PORT=???? as environment variables in both myprivaterepo and this app being tested so an error would pop up saying EADDRINUSE. So I had to update myprivaterepo to use MYPRIVATEREPO_PORT

    There is a ticket raised in Gitlab-ce, who knows when it will be implemented.