I have a Jenkins step as below.
stage('Initialize Namespace') {
when {
expression { params.initNS }
}
steps {
script {
setBuildStatus(processing_test_context, 'Initializing namespace', 'PENDING');
}
sh """ #!/bin/bash
set -e
namespaces="\${kubectl get namespaces -o jsonpath='{range .items[*]}{.metadata.name}{\"\n\"}{end}'}"
echo "\${namespaces}"
if [[ \$namespaces =~ \$NAMESPACE ]]
then
kubectl create namespace $NAMESPACE || true
else
echo "The namespace already exists. Will be using the same"
fi
"""
}
How do I store the output of the command kubectl get namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
in a variable? Currently, the error I am getting is ${kubectl get namespaces -o jsonpath='{range .items[*]}{.metadata.name}{" "}{end}'}: bad substitution
.
How do I escape "
in the command?
CodePudding user response:
Here is a working shell block for the script you provided.
sh"""
#!/bin/bash
namespaces=\$(kubectl get namespaces -o jsonpath='{range .items[*]}{.metadata.name}{\"\\n\"}{end}')
echo "\$namespaces"
if [[ \$namespaces =~ \$NAMESPACE ]]
then
echo "Creating Namespace"
kubectl create namespace \$NAMESPACE || true
else
echo "The namespace already exists. Will be using the same"
fi
"""
If you don't need variable substitution(String interpolation) in your sh
block you can use 3 single quotes rather than using double quotes which will allow you to get rid of multiple escape characters.
On a different note, the following is a different way to get what you need. Here $NAMESPACE has to be not empty always.
sh'''
#!/bin/bash
NS=$(kubectl get namespace $NAMESPACE --ignore-not-found);
echo $NS
if [[ -z "$NS" ]]; then
echo "Creating namespace $NAMESPACE"
kubectl create namespace $NAMESPACE || true
else
echo "The namespace already exists. Will be using the same"
fi
'''