如何通过AWS CLI为EC2安全组入站规则添加描述并动态传入公网IP
Got it, let's get this sorted out for you. The core challenge here is properly embedding your dynamic public IP into the structured IpRanges parameter when using --ip-permissions—since this argument expects a formatted string that pairs the CIDR with its description.
Solution 1: Use a Variable for Cleanliness
First, store your public IP in a variable to avoid quoting headaches and keep the command readable:
# Fetch your current public IP and append /32 to make it a single-host CIDR MY_PUBLIC_IP=$(curl -s https://checkip.amazonaws.com)/32 # Run the AWS CLI command with the pre-defined variable aws ec2 authorize-security-group-ingress \ --group-id sg-12345678 \ --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp='$MY_PUBLIC_IP',Description="Testing"}]' \ --profile xyz
This works because we temporarily close the single quote around the IpRanges value, let bash expand the variable, then re-open the quote to finish the string structure.
Solution 2: Embed curl Directly (One-Liner)
If you prefer to skip the variable, you need to handle quotes carefully. Use double quotes around the IpRanges structure so bash executes the curl command, and escape the inner double quotes for the description:
aws ec2 authorize-security-group-ingress \ --group-id sg-12345678 \ --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges="[{CidrIp=$(curl -s https://checkip.amazonaws.com)/32,Description=\"Testing\"}]" \ --profile xyz
Bonus: Use JSON with jq (More Robust)
For complex rules, using jq to build the JSON structure eliminates quoting mistakes entirely:
aws ec2 authorize-security-group-ingress \ --group-id sg-12345678 \ --ip-permissions "$(jq -n --arg ip "$(curl -s https://checkip.amazonaws.com)/32" '[{ IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{CidrIp: $ip, Description: "Testing"}] }]')" \ --profile xyz
Why Your Initial --cidr + --description Failed
Quick side note: Older versions of the AWS CLI don't support the --description flag when using the simplified --cidr argument. The --description parameter was added later, and it only works reliably with the structured --ip-permissions approach (which is why your second command worked). Updating your AWS CLI to the latest version might let you use --cidr with --description, but the --ip-permissions method is more consistent across versions.
内容的提问来源于stack exchange,提问作者Waseem Mir

