Linux环境下如何从AWS Secrets Manager的JSON输出中提取密码至Shell变量
Got it, let's solve this: you need to pull the password value from the AWS Secrets Manager JSON response and store it in a shell variable var1. Here are a few practical approaches, ordered by reliability:
1. Recommended: Use jq (JSON-aware tool)
This is the safest method because it's purpose-built for parsing JSON, avoiding the pitfalls of regex-based tools when dealing with special characters or unexpected formatting.
First, make sure jq is installed (most Linux distros have it in their repos: sudo apt install jq for Debian/Ubuntu, sudo yum install jq for RHEL/CentOS).
Then run this command:
var1=$(aws secretsmanager get-secret-value --secret-id abc_account --version-stage AWSCURRENT | jq -r '.SecretString | fromjson | .password')
Let's break down what this does:
-rtellsjqto output raw text (no surrounding quotes).SecretStringextracts the escaped JSON string from the top-level responsefromjsonparses that escaped string into a proper JSON object.passwordpulls the value of thepasswordkey from that object
2. Using awk (if jq isn't available)
If you can't install jq, you can use awk to split the output at the right points:
var1=$(aws secretsmanager get-secret-value --secret-id abc_account --version-stage AWSCURRENT | awk -F'"password":"' '{print $2}' | awk -F'"' '{print $1}')
- First
awksplits the line at"password":", grabbing everything after that split - Second
awksplits the result at the next double quote, grabbing the password value before it
3. Using grep + sed
Another regex-based option (note: this can fail if your password contains unusual characters like escaped quotes):
var1=$(aws secretsmanager get-secret-value --secret-id abc_account --version-stage AWSCURRENT | grep -o '"password":"[^"]*"' | sed 's/"password":"\(.*\)"/\1/')
grep -oisolates the exact"password":"PASSWORD111"substringseduses a capture group to extract just the password value inside the quotes
Quick Tip
Always prefer jq when working with JSON in shell scripts—it handles edge cases (like passwords with spaces or special characters) that regex tools can't reliably manage.
内容的提问来源于stack exchange,提问作者cuaspectcox

