Gitlab CI: how to load vars from JSON file

Viewed 479

I'm creating ASP.Net Core applications using Gitlab CI and docker-in-docker. So at first stage I build Dockerfiles and push them in repo, at the second stage I apply yamls to deploy from repo to cluster.

K8S doesn't allow to run containers at port 80 (in my configuration), so I need to expose ports for Dockerfiles.

What I want to do - load correct port numbers from appsettings.json (AspNet config file) in GitLab CI/CD - I don't want to hardcode that values in Gitlab job or in Gitlab Variables.

At the current moment I'm going this way gitlab-ci.yml:

build:
  image: ${CI_REGISTRY}/dockerhub/library/docker:20.10.11
  stage: build
  services:
    - ${CI_REGISTRY}/dockerhub/library/docker:20.10.11-dind
  variables:
    DOCKER_HOST: tcp://localhost:2375
    DOCKER_TLS_CERTDIR: ""
  script:
    - docker build
      -f ./MyApp.Api/Dockerfile
      --build-arg PORT=5076 .
    - docker push ${CI_REGISTRY_IMAGE}/myapp:${tag}

I hardcoded --build_arg to expose correct port.

How to read it value from JSON file?

Json file looks like this:

{
  "MyApp": {
    "ConnectionString": "Host=host;Port=5432;"
  },
  "ClientBaseUrls": {
    "MyApp": "http://my-serv:5076/api",
  }
}

Also I can add additional var to JSON, for example: PORT=5076 but still can't figure out how to read this value in GitLab CI.

1 Answers

You could use jq in a previous job to read from appsettings.json , save them in a script that exports these variables, use this script as artifact and run it in your build job so that env variables are available in your build stage.

You stated that you can add additional vars, so lets assume your .json looks like this:

   {
      "port" : "5678",
      ...
    }

Then your gitlab-ci.yml could look like this:

stages:
  - variables
  - build

variables:
  stage: variables
  image: ubuntu
  before_script:
    - apt-get update
    - apt-get install -y jq 
  script:
    - export PORT=$(cat appsettings.json | jq '.port' )
    - echo "export PORT=$PORT" >> vars.sh
  artifacts:
    paths:
      - vars.sh

build:
  image: ${CI_REGISTRY}/dockerhub/library/docker:20.10.11
  stage: build
  services:
    - ${CI_REGISTRY}/dockerhub/library/docker:20.10.11-dind
  variables:
    DOCKER_HOST: tcp://localhost:2375
    DOCKER_TLS_CERTDIR: ""
  before_script:
    - . ./vars.sh
  script:
    - docker build
      -f ./MyApp.Api/Dockerfile
      --build-arg PORT=$PORT .
    - docker push ${CI_REGISTRY_IMAGE}/myapp:${tag}
Related