Can I add dns name in aws security group
AWS security rules only allow IP ranges, called CIDRs, that you can update with the AWS CLI. However, you can't simply update the CIDR of an existing rule, you need to:
- delete the old rule:
aws ec2 revoke-security-group-ingress ...
- create a new rule:
aws ec2 authorize-security-group-ingress ...
Example
I've found some form of this script useful to encapsulate the steps necessary:
#!/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
Explanation
This method uses the following 3 AWS CLI commands, taken from the example above with the bash scripting removed.
1) Obtain the CIDR IP of a rule in a specific security group by the rule's description. This command uses JMESPath in the query
parameter to return only the data we want:
aws ec2 describe-security-groups --query "SecurityGroups[?GroupName=='MY_SECURITY_GROUP_NAME'].IpPermissions[*].IpRanges[?Description=='MY_RULE_DESCRIPTION'].CidrIp" --output text
2) Remove rule for the old CIDR (succeeds even when rule doesn't exist):
aws ec2 revoke-security-group-ingress --group-name MY_SECURITY_GROUP_NAME --protocol tcp --port 80 --cidr 0.0.0.0/32
3) Add rule for the new CIDR (fails when rule already exists):
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"}]}]'
Security Groups and ACLs are not able to resolve DNS hostnames.
You can use the AWS CLI to script the update of your IP dynamic address:
aws ec2 authorize-security-group-ingress --group-id --protocol tcp --port 22 --cidr /24
http://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-sg.html