Search code examples
jenkinsjenkins-pipeline

Accessing jenkins shell variables within a k8s container


stages
{
    stage('test')
    {
        steps
        {
            withCredentials([string(credentialsId: 'kubeconfigfile', variable: 'KUBECONFIG' )])
            {
                container('deploycontainer')
                {
                    sh 'TEMPFILE=$(mktemp -p "${PWD}" kubeconfig.XXXXX)'
                    sh 'echo "${TEMPFILE}"'
                }
            }
        }        
    }
}

I'm new to creating pipelines and am trying to covert a freestyle job over to a pipeline. I'm trying to create a temp file for a kubeconfig file within the container. I've tried everyway I could think of to access the vars for the shell and not a groovy var.

even trying the below prints nothing on echo:

sh 'TEMPFILE="foo"'
sh 'echo ${TEMPFILE}'

I've tried escaping and using double quotes as well as single and triple quote blocks.

How do you access the shell vars from within the container block/how do you make a temp file and echo it back out within that container block?


Solution

  • With Jenkinsfiles, each sh step runs its own shell. When each shell terminates, all of its state is lost.

    If you want to run multiple shell commands in order, you can do one of two things.

    You can have a long string of commands separated by semi-colons:

    sh 'cmd1; cmd2; cmd3; ...'
    

    Or you can use ''' or """ to extend the commands over multiple lines (note of course that if you use """ then groovy will perform string interpolation):

    sh """
    cmd1
    cmd2
    cmd3
    ...
    """
    

    In your specific case, if you choose option 2, it will look like this:

    sh '''
    TEMPFILE=$(mktemp -p "${PWD}" kubeconfig.XXXXX)
    echo "${TEMPFILE}"
    '''
    

    Caveat

    If you are specifying a particular shebang, and you are using a multiline string, you MUST put the shebang immediately after the quotes, and not on the next line:

    sh """#!/usr/bin/env zsh
    cmd1
    cmd2
    cmd3
    ...
    """