Skip to content

Instantly share code, notes, and snippets.

@leonardobiffi
Created July 25, 2024 16:43
Show Gist options
  • Select an option

  • Save leonardobiffi/f0d0aedbd83ebf598a4e28b0b88edf3e to your computer and use it in GitHub Desktop.

Select an option

Save leonardobiffi/f0d0aedbd83ebf598a4e28b0b88edf3e to your computer and use it in GitHub Desktop.
Get AWS Secrets Manager or Parameter by name
#!/bin/bash
# Default variable values
type=""
name=""
region=""
# Function to display script usage
usage() {
echo "Usage: $0 [OPTIONS]"
echo "Options:"
echo " -h, --help Display this help message"
echo " -t, --type Valid values: secret, parameter"
echo " -n, --name Name of the resource "
echo " -r, --region AWS Region"
}
error() {
echo "[getenv.sh] Error: $1" >&2
exit 1
}
has_argument() {
[[ ("$1" == *=* && -n ${1#*=}) || ( ! -z "$2" && "$2" != -*) ]];
}
extract_argument() {
echo "${2:-${1#*=}}"
}
# Function to handle options and arguments
handle_options() {
while [ $# -gt 0 ]; do
case $1 in
-h | --help)
usage
exit 0
;;
-t | --type*)
if ! has_argument $@; then
error "Type not specified."
usage
exit 1
fi
type=$(extract_argument $@)
shift
;;
-n | --name*)
if ! has_argument $@; then
error "Name not specified."
usage
exit 1
fi
name=$(extract_argument $@)
shift
;;
-r | --region*)
if ! has_argument $@; then
error "Region not specified."
usage
exit 1
fi
region=$(extract_argument $@)
shift
;;
*)
error "Invalid option: $1"
usage
exit 1
;;
esac
shift
done
}
# Main script execution
handle_options "$@"
if [ -z "$type" ]; then
error "Type not specified"
usage
exit 1
fi
if [ -z "$name" ]; then
error "Name not specified"
usage
exit 1
fi
if [ -z "$region" ]; then
error "Region not specified"
usage
exit 1
fi
# Perform the desired actions based on the provided flags and arguments
# Check if aws and jq are installed
if ! command -v aws >/dev/null 2>&1; then
error "awscli is not installed. Please install it and try again"
exit 1
fi
if ! command -v jq >/dev/null 2>&1; then
error "jq is not installed. Please install it and try again"
exit 1
fi
# check if aws credentials are configured
if ! aws sts get-caller-identity >/dev/null 2>&1; then
error "AWS credentials are not configured. Please configure them and try again"
exit 1
fi
if [ "$type" == "parameter" ]; then
# Export the parameters
aws ssm get-parameters-by-path --with-decryption --path $name --region $region \
--query "Parameters[*].{Name:Name,Value:Value}" | sed 's,'"$name/"',,' > env.json
# Convert JSON array to variable statements using jq command line JSON utility tool
jq -jr '.[]|.Name,"=",.Value,"\n"' < env.json
rm env.json
fi
if [ "$type" == "secret" ]; then
# Export the secret
aws secretsmanager get-secret-value --secret-id $name --region $region | \
jq -r '.SecretString' | \
jq -r "to_entries|map(\"\(.key)=\\\"\(.value|tostring)\\\"\")|.[]"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment