8

I have the following sh command in my Jenkinsfile which does not work because it tries to execute the last "DATA" as a command. If I move last "DATA" to the beginning of the line it works but is not as beautiful as I want. Is there a way to the indention in this case?

    sh """
        sshpass -p 'password' ssh -o StrictHostKeyChecking=no appsadm@$backup_registry <<DATA
        sudo /etc/init.d/docker stop || true
        sudo yum remove -y docker-engine.x86_64
        sudo rm -fr /var/lib/docker /var/log/docker
        sudo rpm -iUvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm || true
        sudo yum update -y
        sudo yum -y install docker-io
        sudo sed -i 's#other_args=.*#other_args="--insecure-registry $official_registry:5000"#g' /etc/sysconfig/docker
        sudo /etc/init.d/docker start
        DATA
        """

3 Answers 3

25

I know this is an old question, but I had ran into this at some point, and eventually ended up using stripIndent()

steps {
    echo 'Deploying....'
    sh """
    ssh somewhere <<EOF
    cd somewhere
    do some more stuff
    EOF
    """.stripIndent()
}

That way you can still keep your indentations and formatting

Sign up to request clarification or add additional context in comments.

1 Comment

It is strange. I saw this yesterday and liked the "elegance" of it. However, it didn't work for me. In my case, the ssh somewhere and delimiter did align by spaces, but the pipeline didn't see the EOF properly: even when I used <<EOF. I don't know Groovy, could there be a difference in the use of stripIndent() inside of a script block as opposed to the steps you have?
5

because <<DATA specifies the end of here-doc <<-DATA suppress leading tabs but not spaces

cat <<-DATA
    hello
<tab>DATA

another option is to add spaces in marker

cat << "    DATA"
    hello
    DATA

3 Comments

won't the second option mean that variables in the multi-line string won't be interpreted?
the commands just demonstrate how heredoc works. How the content is interpreted depends on the program which reads input here cat will dysplay the content; in your question will be executed by a shell through ssh and sshpass.
how would you remove spaces as well, not just tabs?
1

Edit: We don't need to use EOF, simply put the semicolon at the end of statement on multiline shell script as shown below

sh """ if [ -d /opt/tomcat/apache-tomcat-8.5.38/webapps/ROOT ] ;
       then ;
            ssh $USERNAME@$DEV_HOSTNAME 'sudo rm -rf /opt/tomcat/apache-tomcat-8.5.38/webapps/ROOT' ;
            echo 'ROOT directory deleted successfully' ;
       fi ;
"""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.