Skip to content

Instantly share code, notes, and snippets.

@gowthamshankar99
Last active July 24, 2023 05:55
Show Gist options
  • Select an option

  • Save gowthamshankar99/f860ae4970c91dc396df117a3e94f2f8 to your computer and use it in GitHub Desktop.

Select an option

Save gowthamshankar99/f860ae4970c91dc396df117a3e94f2f8 to your computer and use it in GitHub Desktop.
Potential ways to variablize Jenkinsfile to avoid using multiple Jenkins file for different environments

Use JENKINS_URL environment variable to restrict environment specific deployment

The below method can be used for dynamically picking a serviceaccont based on the JENKINS_URL as well.

pipeline {
    agent any
    environment {
        ENV_NAME = 'production'
    }
    stages {
        stage('Build') {
            steps {
                // Your build steps here
            }
        }
        stage('Deploy') {
            when {
                expression {
                    // Check if Jenkins URL matches your production environment
                    if (env.JENKINS_URL == 'https://jenkins-production.example.com/' && env.ENV_NAME == 'production') {
                        echo 'Production build on a development server is not allowed.'
                        return false
                    }
                    return true
                }
            }
            steps {
                // Deployment steps for staging environment
            }
        }
    }
}

Pointers

  • if you want to avoid the risk of developers changing the pipeline and accidently deploying code to production - you could do the following

    • Please ensure that the non-production Jenkins server does not possess any production credentials.
    • When employing a secret management tool such as Vault, it is imperative to establish distinct instances of Vault for both development and production environments. It is recommended to integrate the development Jenkins with the dev Vault instance and the production Jenkins with the prod Vault instance. This clear segregation ensures the proper management and safeguarding of sensitive credentials and data, enhancing the overall security posture of the system.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment