Home > front end >  AWS CLI - Create script to add my IP to security group
AWS CLI - Create script to add my IP to security group

Time:11-30

I'm trying to create a script to add my IP adress to AWS VPC security groups somthing like

>  aws ec2 modify-security-group-rules --group-id GROUPID\
> --security-group-rules SecurityGroupRuleId= RULEID\
SecurityGroupRule={IpProtocol:'tcp',FromPort:433,ToPort:433,CidrIpv4:'MYIP'}

But I keep getting different errors like -

IpProtocol:tcp, type: <class 'str'>, valid types: <class 'dict'>

Can anyone please help figure out the correct syntax for this?

UPDATE: I tried a new syntax that seems to work better

SecurityGroupRule={{IpProtocol=tcp},{FromPort=433},{ToPort=433},{CidrIpv4='IP'}}

But now I get a different error from AWS -

Invalid value for portRange. Must specify both from and to ports with TCP/UDP.

UPDATE: For reference - Here's the workaround I used- (based on John Rotenstein answer) Instead of modifying the rule I create a new one each time and save the rule ID so I can delete it next time I run the script

IP=`curl -s http://whatismyip.akamai.com/`
aws ec2 revoke-security-group-ingress \
         --group-id GROUP_ID         \
         --security-group-rule-ids $(cat ruleid_1.txt)
       
    aws ec2 authorize-security-group-ingress --group-id GROUP_ID\
--ip-permissions "IpProtocol"="tcp","FromPort"=433,"ToPort"=443,"IpRanges"="[{CidrIp=$IP/32,Description=Shalev}]"|jq '.SecurityGroupRules[0].SecurityGroupRuleId' -r > ruleid_1.txt

CodePudding user response:

Here's a script I use to add my current IP address to a Security Group:

IP=`curl -s http://whatismyip.akamai.com/`
aws ec2 authorize-security-group-ingress --group-name XXX --protocol tcp --port 22 --cidr $IP/32 --output text

It uses Akamai to retrieve my public IP address and then adds it to the desired Security Group.

Note that there is a limit to the number of rules in a Security Group, so eventually you will need to remove unused entries.

CodePudding user response:

For reference - Here's the workaround I used- (based on John Rotenstein answer) Instead of modifying the rule I create a new one each time and save the rule ID so I can delete it next time I run the script

IP=`curl -s http://whatismyip.akamai.com/`

aws ec2 revoke-security-group-ingress \
         --group-id GROUP_ID         \
         --security-group-rule-ids $(cat ruleid_1.txt)
   


aws ec2 authorize-security-group-ingress --group-id GROUP_ID\
--ip-permissions "IpProtocol"="tcp","FromPort"=433,"ToPort"=443,"IpRanges"="[{CidrIp=$IP/32,Description=Shalev}]"|jq '.SecurityGroupRules[0].SecurityGroupRuleId' -r > ruleid_1.txt
  • Related