Skip to content

Instantly share code, notes, and snippets.

@h053698
Created March 31, 2026 11:43
Show Gist options
  • Select an option

  • Save h053698/fd5f0206b608191ea3bad32b6ecbee4f to your computer and use it in GitHub Desktop.

Select an option

Save h053698/fd5f0206b608191ea3bad32b6ecbee4f to your computer and use it in GitHub Desktop.
Grant Secret Manager Read Value
#!/usr/bin/env bash
set -euo pipefail
# Creates/updates CUSTOMER MANAGED IAM policy only (no prompts, no role attach)
# Improved policy name: AWSSecretsManagerAllowGetSecretValue
# Usage:
# ./scripts/grant-secret-read-role.sh
POLICY_NAME="AWSSecretsManagerAllowGetSecretValue"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
POLICY_ARN="arn:aws:iam::${ACCOUNT_ID}:policy/${POLICY_NAME}"
TMP_POLICY=$(mktemp)
cat > "$TMP_POLICY" <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowGetSecretValueAll",
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": "*"
}
]
}
EOF
echo "Target policy ARN: $POLICY_ARN"
if aws iam get-policy --policy-arn "$POLICY_ARN" >/dev/null 2>&1; then
echo "Policy exists. Updating policy document..."
VERSIONS_JSON=$(aws iam list-policy-versions --policy-arn "$POLICY_ARN" --output json)
COUNT=$(echo "$VERSIONS_JSON" | python3 -c 'import sys,json;j=json.load(sys.stdin);print(len(j["Versions"]))')
if [[ "$COUNT" -ge 5 ]]; then
OLDEST_NON_DEFAULT=$(echo "$VERSIONS_JSON" | python3 -c 'import sys,json;j=json.load(sys.stdin)["Versions"];nd=[v for v in j if not v["IsDefaultVersion"]];nd=sorted(nd,key=lambda x:x["CreateDate"]);print(nd[0]["VersionId"] if nd else "")')
if [[ -n "$OLDEST_NON_DEFAULT" ]]; then
aws iam delete-policy-version --policy-arn "$POLICY_ARN" --version-id "$OLDEST_NON_DEFAULT"
fi
fi
aws iam create-policy-version \
--policy-arn "$POLICY_ARN" \
--policy-document "file://$TMP_POLICY" \
--set-as-default >/dev/null
else
echo "Policy not found. Creating policy..."
aws iam create-policy \
--policy-name "$POLICY_NAME" \
--policy-document "file://$TMP_POLICY" >/dev/null
fi
rm -f "$TMP_POLICY"
echo "Done ✅"
echo "Created/Updated: $POLICY_ARN"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment