amazon-web-servicesdockeraws-ssmdocker-entrypoint

Make docker exit on any command failure in docker-entrypoint.sh


I'm trying to load AWS SSM Parameters in my docker-entrypoint.sh I'm testing the failure case and it continues to the CMD if it fails.

#!/bin/bash
set -eo pipefail

ssm_available() {
  if [ -z ${SSM_BASE_PATH+x} ]; then
    return 1
  fi

  return 0
}

get_ssm_params() {
  aws ssm get-parameters-by-path --no-paginate --path ${SSM_BASE_PATH} --with-decryption --query Parameters | \
  jq -r 'map("\(.Name | sub("'${SSM_BASE_PATH}'";""))=\(.Value)") | join("\n")'
}

exec_with_ssm_parameters() {
  for parameter in `get_ssm_params`; do
    echo "Info: Exporting parameter ${parameter%%=*}"
    export ${parameter}
  done
  exec "$@"
}

main() {
  if ssm_available; then
    echo "Info: Loading SSM Parameters" >&2
    exec_with_ssm_parameters "$@"
  fi

  echo "Info: Starting ..." >&2
  exec "$@"
}

main "$@"

I've tried both set -e and set -eo pipefail but if the aws call fails, it will still continue to start the server.

How do I make Docker stop executing if the there are any failures in docker-entrypoint.sh?

EDIT: I believe it's because the command is completing successfully, but I'm not handling errors in the response.


Solution

  • The command aws ssm get-parameters-by-path --no-paginate --path ${SSM_BASE_PATH} --with-decryption --query Parameters is not failing so will not trigger any non-zero exit code handling.

    Instead you should deal with the empty response from the get_ssm_params function in the exec_with_ssm_parameters function by checking if the response exists.

    Something like the following using the -z flag to test whether the string is empty should resolve your issue:

    exec_with_ssm_parameters() {
      local params=$(get_ssm_params)
    
      if [ -z "$params" ]; then
        echo "Error: No SSM parameters found"
        exit 1
      fi
    
      for parameter in $params; do
        echo "Info: Exporting parameter ${parameter%%=*}"
        export ${parameter}
      done
    
      exec "$@"
    }