Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 "[email protected]"

# 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.

like image 423
Nitesh Avatar asked Jan 05 '18 04:01

Nitesh


Video Answer


1 Answers

Do you have the requirement to always prompt for the credentials? If not, you could store them in the Jenkins credential store and retrieve them via withCredentials step from the Jenkins Credentials Binding plugin. That way they are hidden in the logs if you do the build within the closure.

withCredentials([usernamePassword(
  credentialsId: 'privateGitCredentials',
  usernameVariable: 'USERNAME',
  passwordVariable: 'PASSWORD'
)]) {
  sh "docker build --build-arg username=$USERNAME --build-arg password=$PASSWORD -t <your tag> ."
}
like image 103
Christopher Avatar answered Sep 23 '22 05:09

Christopher