使用AWS CLI批量更新IP描述遇引号问题,求代码改写方案
The problem here is that bash doesn’t handle nested single quotes well, and your ${line} variable wasn’t properly quoted—this can break things even if your CIDRs don’t have weird characters, it’s still a best practice to quote variables. Plus, AWS CLI plays nicer with double-quoted JSON in bash to avoid escaping headaches.
Here’s the revised script that fixes the quoting problems and properly processes each IP from your ip_list file:
while read -r line; do aws ec2 update-security-group-rule-descriptions-ingress \ --group-id sg-123456 \ --region us-east-2 \ --ip-permissions "[{\"IpProtocol\": \"tcp\", \"FromPort\": 443, \"ToPort\": 443, \"IpRanges\": [{\"CidrIp\": \"${line}\", \"Description\": \"Meaningful description\"}]}]" done < ip_list
Key changes made:
- Switched all inner JSON quotes to double quotes, escaping them with backslashes (
\") so bash treats them as part of the string instead of closing the outer quote. - Wrapped
${line}in double quotes ("${line}") to ensure the CIDR is passed as a single, properly quoted value in the JSON. - Kept the outer square brackets since
--ip-permissionsexpects a list of permission objects.
If you want to avoid escaping every double quote (for better readability), you can use a here-doc to build the JSON instead:
while read -r line; do permissions=$(cat <<EOF [{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "IpRanges": [{"CidrIp": "${line}", "Description": "Meaningful description"}]}] EOF ) aws ec2 update-security-group-rule-descriptions-ingress \ --group-id sg-123456 \ --region us-east-2 \ --ip-permissions "$permissions" done < ip_list
This here-doc approach makes the JSON easier to edit without messy escapes. Just make sure the EOF lines are left unindented (or use <<-EOF and indent with tabs if you prefer formatted code).
Either version will work reliably— the core fix is ensuring bash doesn’t mangle your quotes or variables when passing the JSON to AWS CLI.
内容的提问来源于stack exchange,提问作者user3299633

