Docker – How to use git credentials from Jenkins pipeline input into docker file

devopsdockerJenkinsjenkins-pipeline

I am trying to load Jenkins pipeline script from SCM. I have to build a docker image and push it to GCR. In the docker image, I need to install private git repositories. Here, I am trying to get git username password from Jenkins input. But I'm not sure how I can use it in the Dockerfile to pull the git repo. These are my Jenkinsfile and Dockerfile in SCM. Any suggestions?

Jenkinsfile :

node {
def app

stage('Clone repository') {
    checkout scm

    def COMMITHASH = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
    echo ("Commit hash: "+COMMITHASH.substring(0,7))
}

stage('Build image') {

    timeout(time: 600, unit: 'SECONDS') { 
        gitUser = input(
           id: 'gitUser', 
           message: 'Please enter git credentials :', 
           parameters: [
           [$class: 'TextParameterDefinition', defaultValue: "", description: 'Git user name', name: 'username'],
           [$class: 'PasswordParameterDefinition', defaultValue: "", description: 'Git password', name: 'password']
        ])
    }

    /* Build docker image */
    println('Build image stage');
    app = docker.build("testBuild")

}

stage('Push image') {
    /* Push image to GCR */

    docker.withRegistry('https://us.gcr.io', 'gcr:***') {
        app.push("${env.BUILD_NUMBER}")
        app.push("latest")
    }
}
}

Dockerfile :

# use a ubuntu 16.04 base image
FROM ubuntu:16.04

MAINTAINER "someuser@company.com"

# Set environment variables
ENV DEBIAN_FRONTEND noninteractive
ENV LC_ALL C.UTF-8

# Upgrade the system
RUN apt-get update && apt-get -y upgrade && apt-get install -y python-software-properties software-properties-common

# Install cert bot and apache
RUN apt-get install -y apache2

#Enable apache modules
RUN a2enmod ssl 
RUN a2enmod headers
RUN a2enmod rewrite

# Create directory for web application
RUN mkdir -p /var/www/myApp


# Expose ssl port
EXPOSE 443

I want to install my private bitbucket repository in /var/www/myApp. Also, I want to avoid ssh authentication.

Best Answer

You should pass your git username and password as environment variables during docker build and then call these variables inside Dockerfile.

Example Dockerfile -

FROM test
ARG username
ARG password
RUN git clone https://${username}:${password}@github.com/private-repo-name.git

Build command:

docker build --build-arg username=$git_username --build-arg password=$git_password -t <your tag> .