Search code examples
bashamazon-web-servicesaws-cliaws-secrets-manager

Bash: How to catch error from AWS Cli command?


I'm trying to do a try/except in my bash script. Basically, I just want to retrieve a secret from SecretsManager, and check if the cli command raises an error.

I tried something like this but it errors out before it flows through the if/else

  command=$(aws secretsmanager get-secret-value --secret-id ${secret_name} --query SecretString --output text | jq . 2>&1)
  if [[ "${command}" =~ "An error occurred (ResourceNotFoundException)" ]]; then
    echo "Configuration does not exist in SecretsManager. Unable to initialize Metaflow settings"
  else
    echo "Configuration exists in SecretsManager. Initializing Metaflow settings"
    echo ${command} > ~/.metaflowconfig/config.json
  fi

The desired result would be to check if the cli command returns an error. If it does not, then set the secret to local config file. If it does, then print that "Unable to initialize settings".


Solution

  • The main problem of your script is that you are piping the output of the CLI command directly to jq, which prevents your logic from working correctly. Here's how I would do it:

    #!/bin/bash
    secret_name="..."
    command_output=$(aws secretsmanager get-secret-value --secret-id $secret_name --query SecretString --output text 2>&1)
    command_exit_code=$?
    
    if [[ "$command_exit_code" -ne 0 ]]; then
      if [[ "${command_output}" =~ "An error occurred (ResourceNotFoundException)" ]]; then
        echo "Configuration does not exist in SecretsManager. Unable to initialize Metaflow settings"
      fi
      # other error cases you might want to deal with
    else
        echo "Configuration exists in SecretsManager. Initializing Metaflow settings"
        echo "${command_output}" | jq '.' > ~/.metaflowconfig/config.json
    fi