DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

Jenkins

pipeline {
agent any

parameters {
    choice(name: 'ENVIRONMENT', choices: ['dev1', 'dev2', 'sit', 'qc', 'uat'], description: 'Select the environment')
    string(name: 'DB_NAME', defaultValue: 'my_database', description: 'Enter the Database Name')
    string(name: 'SQL_FILE', defaultValue: 'queries.sql', description: 'SQL file to execute')
}

environment {
    DB_HOST = ""
    DB_USER = ""
    DB_PASS = ""
}

stages {
    stage('Set DB Credentials') {
        steps {
            script {
                def dbConfig = [
                    dev1: [host: "192.168.1.101", user: credentials('DB_USER_DEV1'), pass: credentials('DB_PASS_DEV1')],
                    dev2: [host: "192.168.1.102", user: credentials('DB_USER_DEV2'), pass: credentials('DB_PASS_DEV2')],
                    sit:  [host: "192.168.1.103", user: credentials('DB_USER_SIT'),  pass: credentials('DB_PASS_SIT')],
                    qc:   [host: "192.168.1.104", user: credentials('DB_USER_QC'),   pass: credentials('DB_PASS_QC')],
                    uat:  [host: "192.168.1.105", user: credentials('DB_USER_UAT'),  pass: credentials('DB_PASS_UAT')]
                ]

                env.DB_HOST = dbConfig[params.ENVIRONMENT].host
                env.DB_USER = dbConfig[params.ENVIRONMENT].user
                env.DB_PASS = dbConfig[params.ENVIRONMENT].pass
            }
        }
    }

    stage('Clone Repository') {
        steps {
            checkout scm  // Uses Git repository settings from Jenkins job
        }
    }

    stage('Execute SQL Queries') {
        steps {
            script {
                sh """
                ssh user@${DB_HOST} "
                mysql -u ${DB_USER} -p${DB_PASS} -D ${DB_NAME} < ${WORKSPACE}/${SQL_FILE}
                "
                """
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (2)

Collapse
 
abhishek_gupta_8fa44f5e66 profile image
Abhishek Gupta

linux_host: "10.0.0.1", linux_user: "dev1_user"]

Collapse
 
pawan07 profile image
Pawan Tiwari

withCredentials([
usernamePassword(credentialsId: 'db-dev', usernameVariable: 'DEV_USER', passwordVariable: 'DEV_PASS'),
usernamePassword(credentialsId: 'db-uat', usernameVariable: 'UAT_USER', passwordVariable: 'UAT_PASS')
]) {
dbConfig = [
"dev" : [user: env.DEV_USER, pass: env.DEV_PASS],
"uat" : [user: env.UAT_USER, pass: env.UAT_PASS]
]
}