AWS 安全规则仅允许您可以使用 AWS CLI 更新的 IP 范围(称为 CIDRs)。但是,您不能简单地更新现有规则的 CIDR,您需要:
- 删除旧规则:
aws ec2 revoke-security-group-ingress ...
- 创建新规则:
aws ec2 authorize-security-group-ingress ...
示例
我发现此脚本的某种形式可用于封装必要的步骤:
#!/bin/bash
# == Script Config ===================
# The rule description is used to determine the rule that should be updated.
RULE_DESCRIPTION=My-Rule-Description
SECURITY_GROUP_NAME=My-Security-Group-Name
# ====================================
OLD_CIDR_IP=`aws ec2 describe-security-groups --query "SecurityGroups[?GroupName=='"$SECURITY_GROUP_NAME"'].IpPermissions[*].IpRanges[?Description=='"$RULE_DESCRIPTION"'].CidrIp" --output text`
NEW_IP=`curl -s http://checkip.amazonaws.com`
NEW_CIDR_IP=$NEW_IP'/32'
# If IP has changed and the old IP could be obtained, remove the old rule
if [[ $OLD_CIDR_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
aws ec2 revoke-security-group-ingress --group-name $SECURITY_GROUP_NAME --protocol tcp --port 8080 --cidr $OLD_CIDR_IP
fi
# If the IP has changed and the new IP could be obtained, create a new rule
if [[ $NEW_IP != "" ]] && [[ $OLD_CIDR_IP != $NEW_CIDR_IP ]]; then
aws ec2 authorize-security-group-ingress --group-name $SECURITY_GROUP_NAME --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "IpRanges": [{"CidrIp": "'$NEW_CIDR_IP'", "Description": "'$RULE_DESCRIPTION'"}]}]'
fi
说明
此方法使用以下 3 个 AWS CLI 命令,取自上面的示例,删除了 bash 脚本。
1) 通过规则描述获取特定安全组中规则的CIDR IP。此命令在query 参数中使用JMESPath 仅返回我们想要的数据:
aws ec2 describe-security-groups --query "SecurityGroups[?GroupName=='MY_SECURITY_GROUP_NAME'].IpPermissions[*].IpRanges[?Description=='MY_RULE_DESCRIPTION'].CidrIp" --output text
2) 删除旧 CIDR 的规则(即使规则不存在也会成功):
aws ec2 revoke-security-group-ingress --group-name MY_SECURITY_GROUP_NAME --protocol tcp --port 80 --cidr 0.0.0.0/32
3) 为新 CIDR 添加规则(规则已存在时失败):
aws ec2 authorize-security-group-ingress --group-name MY_SECURITY_GROUP_NAME --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "IpRanges": [{"CidrIp": "1.1.1.1/32", "Description": "MY_RULE_DESCRIPTION"}]}]'