I am trying to run a series for commands for aws through a Jenkins job but whenever it comes to the if condition, it throws an error
Here are the list of commands
echo '****** Updating ASG ********'
aws autoscaling update-auto-scaling-group --auto-scaling-group-name test-asg --desired-capacity 2 --min-size 2 --max-size 6
sleep 200
echo '****** Initiating Instance Refresh ********'
aws autoscaling start-instance-refresh --auto-scaling-group-name test-asg --preferences '{"InstanceWarmup": 300, "MinHealthyPercentage": 100}'
while true;
do
instance_refresh_status=$(aws autoscaling describe-instance-refreshes --auto-scaling-group-name test-asg --query "InstanceRefreshes[0].Status" --output text --region us-east-1)
if (( "$instance_refresh_status" == "Successful" )); then
break
fi
sleep 10
done
echo '****** Finished Instance Refresh ********'
echo '****** Updating ASG back to normal ********'
aws autoscaling update-auto-scaling-group --auto-scaling-group-name test-asg --desired-capacity 1 --min-size 1
The error I get is this in the Jenkins output
instance_refresh_status=InProgress
InProgress == Successful
/tmp/jenkins8251579523029552853.sh: 10: /tmp/jenkins8251579523029552853.sh: InProgress: not found
No matter what I try to wrap the if condition in, (), (()), [], [[]] I get the same error as above.
Can you please help me solve this?
CodePudding user response:
Use if [ "$instance_refresh_status" = "Successful" ]; then
(note the single square brackets and single equal sign).
There are two problems in your version: first, (( ))
is a bashism, and your script is not running under bash. In any POSIX-compliant shell, ( )
runs its contents (as normal shell commands) in a subshell. bash (and some other shells) treat (( ))
differently, but in a basic POSIX shell like dash (which I suspect you're running under), it just runs its contents in two layers of subshell. So it's running "InProgress" == "Successful"
in a double-sub-shell, which treats InProgress
as a command and ==
and Successful
as arguments to it, and gets a "not found" error looking for the command.
If you want to use bash features (or don't know which features are bashisms and which will work in other shells), you should start the script with a proper bash-specific shebang line, like #!/bin/bash
or #!/usr/bin/env bash
(and don't override it by running the script with the sh
command).
The second problem is that in bash, (( ))
does integer arithmetic evaluation. Given (( "InProgress" == "Successful" ))
, it will try to evaluate InProgress
and Successful
as integers. The details aren't important here, but essentially they'll both evaluate as 0, so since 0 == 0
is true, the test will come out as true even though they're completely different strings.
To do string comparisons, use [ ]
or [[ ]]
, and since [[ ]]
is another bashism (as is ==
inside them), I'd recommend using [ = ]
at least until you're certain of which shell your script is running under.