Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/65648804/accessing-jenkins-shell-variables-within-a-k8s-container

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...