使用Python Boto3为AWS安全组入站规则加描述遇错咨询
Absolutely! You can add descriptions to individual security group ingress rule entries—AWS fully supports this feature, and the official syntax you referenced is correct. The error you're seeing is almost certainly due to a small syntax oversight in your code.
Let's Fix the Syntax Issue
Looking at your code snippet, the critical mistake is that your CidrIp value isn't wrapped in quotes. In Python, 192.168.2.3/32 will be interpreted as a division operation instead of a string, which causes the API call to fail. Here's the corrected version of your code:
sg.authorize_ingress( DryRun=False, IpPermissions=[ { 'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [ { 'CidrIp': '192.168.2.3/32', # Now properly quoted as a string 'Description': 'My dynamic SSH access' # Your custom description } ] } ] )
Additional Checks
Verify Boto3 Version: Ensure you're using a recent version of boto3. The
Descriptionfield forIpRangeswas added in boto3 version 1.10.0 (circa 2019), so if your installation is outdated, you might encounter compatibility issues. You can update boto3 with:pip install --upgrade boto3Confirm the Rule Was Applied: After running the corrected code, you can verify the description exists by fetching the security group details:
# Fetch the security group details sg_details = sg.describe_security_groups(GroupIds=[sg.id]) # Iterate through ingress rules to check descriptions for rule in sg_details['SecurityGroups'][0]['IpPermissions']: for ip_range in rule['IpRanges']: print(f"CIDR: {ip_range['CidrIp']} | Description: {ip_range.get('Description', 'No description set')}")
Key Takeaway
Yes, every individual IpRanges entry in a security group ingress rule can have its own unique description. This is a useful feature for documenting why a specific IP is allowed access (e.g., "Home office SSH" or "Dev server CI/CD").
内容的提问来源于stack exchange,提问作者user365270

