I am creating a pipeline using jenkins, trying to add a logic where if the terraform-plan is successful then only it will proceed with apply, therefore need get the return value as 0/1/2 from the sh terraform plan command but getting an error as below:
+ gt
+ echo 2
2
C:/Users/Smi/.jenkins/workspace/Pipe_Groovy#tmp/durable-33bd46fb/script.sh: line 2: gt: command not found
+ status
C:/Users/Smi/.jenkins/workspace/Pipe_Groovy#tmp/durable-33bd46fb/script.sh: line 2: status: command not found
[Pipeline] }
Below is the code:
sh "terraform init"
sh "terraform get"
sh "set +e; terraform plan -out=plan.out -detailed-exitcode; echo \$? > status"
def exitCode = readFile('status').trim()
def apply = false
echo "Terraform Plan Exit Code: ${exitCode}"
if (exitCode == "0") {
currentBuild.result = 'SUCCESS'
}
if (exitCode == "1") {
slackSend channel: '#ci', color: '#0080ff', message: "Plan Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'FAILURE'
}
if (exitCode == "2") {
stash name: "plan", includes: "plan.out"
slackSend channel: '#ci', color: 'good', message: "Plan Awaiting Approval: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
try {
input message: 'Apply Plan?', ok: 'Apply'
apply = true
} catch (err) {
slackSend channel: '#ci', color: 'warning', message: "Plan Discarded: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
apply = false
currentBuild.result = 'UNSTABLE'
}
}
Please advice
Shell is trying to find a command named gt and fails, so your job fails at this step. You probably wanted to use > instead.
There is a way to get the exit code of a bash command without redirecting it into a file and than reading it:
def status = sh(returnStatus: true, script: "set +e; terraform plan -out=plan.out -detailed-exitcode")
Do something as follows:
#!/bin/bash -xe
set +e
/terraform plan -var-file="${env}-custom.tfvars" -refresh=false -detailed-exitcode
PLAN_ECODE=$?
echo ${PLAN_ECODE}
set -e
if [ "${PLAN_ECODE}" -eq 1 ]; then
echo "ERROR!!! something is wrong planning!"
exit 1
elif [ "${PLAN_ECODE}" -eq 0 ]; then
echo "No changes!"
elif [ "${PLAN_ECODE}" -eq 2 ]; then
echo "Applying in progress!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
/terraform apply -auto-approve -var-file="${env}-custom.tfvars"
echo "$i has been updated (check logs above for details)" >> /tmp/logs.txt
fi
Related
I'm pretty new to Jenkins, so not totally clear on how to assign/read variables.
I have a jenkinsfile with a couple stages and a bunch of steps. In one of the steps, I want to run a PowerShell script but it isn't accomplishing the intent. The problem is, when I'm in Jenkins and I go to the Console Output to troubleshoot why the PowerShell script isn't working, I don't see any of the output from the powershell script, I just see this:
[Pipeline] {
[Pipeline] powershell (Test PowerShell Script)
[Pipeline] }
Here's a trimmed-down version of my code:
stages {
stage('Stage 1') {
agent { node {
label "Windows"
customWorkspace "D:\\Path"
}}
steps {
dir('Directory') {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
}
}
}
}
}
I tried using the code provided in this Jenkins article:
steps {
dir('Directory') {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
def msg = powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
println msg
}
}
}
This threw an error:
WorkflowScript: 135: Expected a step # line 135, column 25.
def msg = powershell(
^
I also tried putting it inside a node:
steps {
dir('Directory') {
node {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
def msg = powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
println msg
}
}
}
}
But it threw an error that the node is missing a label, and when I tried adding a label it threw another error.
So what's the right way to go about this? I just want to capture the output from the PowerShell script and see it so I can troubleshoot why it isn't working.
I'm trying to add some conditional logic to my Azure DevOps pipeline to perform actions based on if there are pending changes in the Git repository. I've created a PowerShell script to check for changes and set a variable, which is working:
$gitStatus = (git status --porcelain) | Out-String
if ($gitStatus) {
Write-Host "##vso[task.setvariable variable=changes;]true"
Write-Host "##[debug]Changes found"
} else {
Write-Host "##vso[task.setvariable variable=changes;]false"
Write-Host "##[debug]No changes found"
}
I can then output the resulting value of "changes" in my pipeline as follows:
- script: echo Output - $(changes)
This returns "Output - true" as expected
If I then add the following to my YAML...
- ${{ if eq(variables.changes, true) }}:
- script: echo Changes = True
- ${{ else }}:
- script: echo Changes = False
I always receive "Changes = False"
Any help would be gratefully received.
Thanks to input from 4c74356b41 I've come up with the following solution:
- script: echo Changes = True
condition: eq(variables.changes, true)
- script: echo Changes = False
condition: ne(variables.changes, true)
The final pipeline will call templates with the required actions to be performed based on the result of the check, but the above works well enough to prove the concept.
I have CircleCI setup and running fine normally, it will helps with creating deployment for me. Today I have suddenly had an issue with the step in creating the deployment due to an error related to kubernetes.
I have the config.yml followed the doc from https://circleci.com/developer/orbs/orb/circleci/kubernetes
Here is my version of setup in the config file:
version: 2.1
orbs:
kube-orb: circleci/kubernetes#1.3.0
commands:
docker-check:
steps:
- docker/check:
docker-username: MY_USERNAME
docker-password: MY_PASS
registry: $DOCKER_REGISTRY
jobs:
create-deployment:
executor: aws-eks/python3
parameters:
cluster-name:
description: Name of the EKS cluster
type: string
steps:
- checkout
# It failed on this step
- kube-orb/delete-resource:
now: true
resource-names: my-frontend-deployment
resource-types: deployments
wait: true
Below is a copy of the error log
#!/bin/bash -eo pipefail
#!/bin/bash
RESOURCE_FILE_PATH=$(eval echo "$PARAM_RESOURCE_FILE_PATH")
RESOURCE_TYPES=$(eval echo "$PARAM_RESOURCE_TYPES")
RESOURCE_NAMES=$(eval echo "$PARAM_RESOURCE_NAMES")
LABEL_SELECTOR=$(eval echo "$PARAM_LABEL_SELECTOR")
ALL=$(eval echo "$PARAM_ALL")
CASCADE=$(eval echo "$PARAM_CASCADE")
FORCE=$(eval echo "$PARAM_FORCE")
GRACE_PERIOD=$(eval echo "$PARAM_GRACE_PERIOD")
IGNORE_NOT_FOUND=$(eval echo "$PARAM_IGNORE_NOT_FOUND")
NOW=$(eval echo "$PARAM_NOW")
WAIT=$(eval echo "$PARAM_WAIT")
NAMESPACE=$(eval echo "$PARAM_NAMESPACE")
DRY_RUN=$(eval echo "$PARAM_DRY_RUN")
KUSTOMIZE=$(eval echo "$PARAM_KUSTOMIZE")
if [ -n "${RESOURCE_FILE_PATH}" ]; then
if [ "${KUSTOMIZE}" == "1" ]; then
set -- "$#" -k
else
set -- "$#" -f
fi
set -- "$#" "${RESOURCE_FILE_PATH}"
elif [ -n "${RESOURCE_TYPES}" ]; then
set -- "$#" "${RESOURCE_TYPES}"
if [ -n "${RESOURCE_NAMES}" ]; then
set -- "$#" "${RESOURCE_NAMES}"
elif [ -n "${LABEL_SELECTOR}" ]; then
set -- "$#" -l
set -- "$#" "${LABEL_SELECTOR}"
fi
fi
if [ "${ALL}" == "true" ]; then
set -- "$#" --all=true
fi
if [ "${FORCE}" == "true" ]; then
set -- "$#" --force=true
fi
if [ "${GRACE_PERIOD}" != "-1" ]; then
set -- "$#" --grace-period="${GRACE_PERIOD}"
fi
if [ "${IGNORE_NOT_FOUND}" == "true" ]; then
set -- "$#" --ignore-not-found=true
fi
if [ "${NOW}" == "true" ]; then
set -- "$#" --now=true
fi
if [ -n "${NAMESPACE}" ]; then
set -- "$#" --namespace="${NAMESPACE}"
fi
if [ -n "${DRY_RUN}" ]; then
set -- "$#" --dry-run="${DRY_RUN}"
fi
set -- "$#" --wait="${WAIT}"
set -- "$#" --cascade="${CASCADE}"
if [ "$SHOW_EKSCTL_COMMAND" == "1" ]; then
set -x
fi
kubectl delete "$#"
if [ "$SHOW_EKSCTL_COMMAND" == "1" ]; then
set +x
fi
error: exec plugin: invalid apiVersion "client.authentication.k8s.io/v1alpha1"
Exited with code exit status 1
CircleCI received exit code 1
Does anyone have idea what is wrong with it? Im not sure whether the issue is happening on Circle CI side or Kubernetes side.
I was facing the exact issue since yesterday morning (16 hours ago). Then taking #Gavy's advice, I simply added this in my config.yml:
steps:
- checkout
# !!! HERE !!!
- kubernetes/install-kubectl:
kubectl-version: v1.23.5
- run:
And now it works. Hope it helps.
been trying several trial and errors on where or how to cut the string in the variable and assign to a new variable to be used by jenkins stage. Normally just removing -TEST Jenkins pipeline indicated below:
properties([
[$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false],
parameters([choice(choices: ['SQA-ENV-CLONE', 'DEV-ENV-CLONE'],
description: 'Select the ENV', name: 'ENV')])])
pipeline {
agent any
stages {
stage('VALIDATE ENVIRONMENT') {
def ACTIVE = sh(returnStdout: true, script: "echo $ENV | sed -e 's/-CLONE//g'")
steps {
echo 'Checking 1st the ${ACTIVE}'
}
}
}
}
Error I'm getting
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 6: Not a valid stage section definition: "def ACTIVE = sh(returnStdout: true, script: "echo $ENV | sed -e 's/-CLONE//g'")". Some extra configuration is required. # line 6, column 9.
stage('VALIDATE ENVIRONMENT') {
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:330)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
Lets say I choose "DEV-ENV-CLONE" as the value I'm expecting to have a successful build with this output:
Checking 1st the DEV-ENV
You need move the def ACTIVE = sh(...) into pipeline step script, They are Groovy script, only can be wrapped by script step.
stage('VALIDATE ENVIRONMENT') {
steps {
script {
ACTIVE = sh(
returnStdout: true,
script: "echo $ENV | sed -e 's/-CLONE//g'"
).trim()
}
echo "Checking 1st the ${ACTIVE}"
}
}
I'm trying to launch a node process as a service using forever, but the configuration is not working correctly. What's wrong with it?
execute "npm install -g forever"
restart_command_string = "forever restart /#{studio_server_folder}/#{studio_server_script}"
reload_command_string = "forever restart /#{studio_server_folder}/#{studio_server_script}"
start_command_string = "forever start /#{studio_server_folder}/#{studio_server_script}"
stop_command_string = "forever stop /#{studio_server_folder}/#{studio_server_script}"
status_command_string = "if [ $(forever list | grep -c \"studio-server\") -gt 0 ]; then echo 1; else echo 0; fi"
# execute "if [ $(forever list | grep -c \"studio-server\") -gt 0 ]; then #{restart_command_string}; else #{start_command}; fi"
service 'studio-server' do
supports :status => true, :restart => true, :reload => true
start_command start_command_string
reload_command reload_command_string
stop_command stop_command_string
status_command status_command_string
restart_command restart_command_string
action [:start]
end
execute 'service --status-all >> /servicestatus'
That status command isn't a command, it is a fragment of bash script and thus is unlikely to be working. In general I would highly recommend using a real service manager like supervisord or systemd.