简体   繁体   中英

AWS EKS CLI command - if/else not working

I'm trying to do a basic if/else that checks to see if a cluster already exists before creating another of that name. This is the entire section;

 cluster=$(aws eks list-clusters | jq -r ".clusters" | grep mycluster_test)
 
 if [ $? -eq 0 ]; then
     echo "this worked, the cluster is $cluster"
 else
     echo "no cluster by this name"
 fi

There is no cluster with this name, and when I run the script it returns nothing. But I don't understand why it's not returning the else statement

I do have a cluster called 'mycluster_new' and when I grep for this, the first echo statement is returned, so can I please get help on why the else statement is failing. Thanks

try this

if your vairabe is string

if [[ $cluster == 1 ]]; then

if your variable is integer

if [[ $cluster -eq 1 ]]; then

Managed to resolve this by checking if the string was empty and ran a check that would continue regardless of if it was empty or not.

CLUSTER=my_eks_cluster

CHECK_NAME=$(aws eks list-clusters | jq -r ".clusters" | grep $CLUSTER || true)

then ran a check for this;

    if [ "$CHECK_NAME" != "" ]; then
        echo "There is already a cluster by this name; $CHECK_NAME. Cannot build another"
        exit 1
    else
        echo "No cluster by this name $CLUSTER, will continue with terraform"
    fi

if you really want to go ahead with your old way, you can always use '-z' to check if the string is null

 if [ -z "$cluster" ]; then
     echo "this worked, the cluster is $cluster"
 else
     echo "no cluster by this name"
 fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM