Search code examples
bashstdoutaws-clistderr

cant suppress or use an AWS-CLI error in bash


i have a simple script that i want to display specific information from AWS using AWS CLI.

for example:

get_cluster_name() {
EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME}) && \
echo $EKS_NAME | jq -r .cluster.name}

the output when the cluster exist is ok, i get the name of the cluster.

when the cluster does not exist, i get:

An error occurred (ResourceNotFoundException) when calling the DescribeCluster operation: No cluster found for name: example_cluster.

my goal is to get an empty output when a cluster is not found. for that i wanted to use the return code in a condition or a string lookup in the output.

the issue is that the output is not stdout or stderr, therefor i cant even direct it to /dev/null just to silence the error.

how can i make this code work properly?:

[[ $(get_cluster_name) =~ "ResourceNotFoundException" ]] && echo "EKS Cluster:....$(get_cluster_name)"

or

[[ $(get_cluster_name) ]] && echo "EKS Cluster:....$(get_cluster_name)"

Thank you.


Solution

  • Here's a consideration, and expansion on my comments. Again you're getting a stderr response when no cluster is found, so this makes this pretty straightforward.

    Using >2 /dev/null to suppress that return message in stderr. Then using ret=$? to capture the return code.

    get_cluster_name() {
      EKS_NAME=$(aws eks describe-cluster --name ${CUSTOMER_NAME} 2> /dev/null);
      ret=$?
      if [ $ret -eq 0 ]; then
         echo $EKS_NAME | jq -r .cluster.name
         return 0
      else
         return $ret
      fi
    }
    

    You can do the same thing now when you call the function as your error will propagate from aws command up the stack:

    cluster=$(get_cluster_name)
    ret=$?
    if [ $ret -eq 0 ]; then
      echo $cluster
    else
      echo "failed to find cluster. Error code: $ret"
    fi
    

    As an example.