skip to Main Content

How to get the output of kubectl describe deployment nginx | grep Image in an environment variable?

My code:

stage('Deployment'){
    script {                                   
        sh """
        export KUBECONFIG=/tmp/kubeconfig
        kubectl describe deployment nginx | grep Image"""
    }
}

2

Answers


  1. You can use the syntax:

    someVariable = sh(returnStdout: true, script: some_script).trim()
    
    Login or Signup to reply.
  2. In this situation, you can access the environment variables in the pipeline scope within the env object, and assign values to its members to initialize new environment variables. You can also utilize the optional returnStdout parameter to the sh step method to return the stdout of the method, and therefore assign it to a Groovy variable (because it is within the script block in the pipeline).

    script {             
      env.IMAGE = sh(script: 'export KUBECONFIG=/tmp/kubeconfig && kubectl describe deployment nginx | grep Image', returnStdout: true).trim()
    }
    

    Note you would also want to place the KUBECONFIG environment variable within the environment directive at the pipeline scope instead (unless the kubeconfig will be different in different scopes):

    pipeline {
      environment { KUBECONFIG = '/tmp/kubeconfig' }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search