Search code examples
dockerjenkinsgroovydsljenkins-job-dsl

How to parameterize jenkins DSL job with pipeline script & docker-compose.yaml


I've created a DSL job nv_dsl.groovy as below,

import groovy.text.SimpleTemplateEngine

def fileContents = readFileFromWorkspace "nv_pipeline.groovy" 
def fileContents1 = readFileFromWorkspace "docker-compose.yaml"
def engine = new SimpleTemplateEngine()

template = engine.createTemplate(fileContents).make(binding.getVariables()).toString()

template1 = engine.createTemplate(fileContents1).make(binding.getVariables()).toString()


pipelineJob("${DSL_JOB}") {

  definition {
    cps { 
        script(template)
    }
  }
}

nv_pipeline.groovy as follows,

pipeline {
  agent any

  environment {
    REPO = repository
  }

  parameters {
    choice name: "ENVIRONMENT", choices: environments
  }

  stages {
    stage('Deploy') {
      steps {
          echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
      }
    }
  }
}

Below is my docker-compose.yml file

version: "3.3"
services:
${SERVICES}:
    restart: always
    container_name: ${CONTAINER_NAME}
    build:
      context: ${CONTEXT}
      args:
        NODE: ${NODE_ENV}
    ports:
        - ${PORTS}
    environment:
      NODE_ENV: ${NODE_ENV}
    volumes:
      - ${VOLUMES}

Here, how can I add my docker-compose.yml file to Jenkins DSL i.e nv_dsl.groovy, so that I can able to pass parameters from Jenkins DSL that apply to the docker-compose.yml file?

While building a pipeline job, I'm getting the error "The CONTAINER_NAME variable is not set. Defaulting to a blank string".


Solution

  • I've added environment variables in Jenkins script whose variables I need to parameterize to YAML file as below and it worked for me as expected,

    pipeline {
      agent any
    
     environment {
       CONTAINER_NAME = "${CONTAINER_NAME}"
       PORTS = "${PORTS}"
       VOLUMES = "${VOLUMES}"
       NODE_ENV = "${NODE_ENV}"
       IMAGE = "${IMAGE}"
     }
    
     parameters {
       choice name: "ENVIRONMENT", choices: environments
     }
    
     stages {
       stage('Deploy') {
         steps {
           echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
         }
       }
     }
    }