User guide

If you attempt to create a security group with the same name as an existing security group,
createSecurityGroup throws an exception.
By default, a new security group does not allow any inbound traffic to your Amazon EC2 instance.To
allow inbound traffic, you must explicitly authorize security group ingress.You can authorize ingress for
individual IP addresses, for a range of IP addresses, for a specific protocol, and for TCP/UDP ports.
To authorize security group ingress
1. Create and initialize an IpPermission instance. Use the withIpRanges method to set the range of
IP addresses to authorize ingress for, and use the withIpProtocol method to set the IP protocol. Use
the withFromPort and withToPort methods to specify range of ports to authorize ingress for, as
follows:
IpPermission ipPermission =
new IpPermission();
ipPermission.withIpRanges("111.111.111.111/32", "150.150.150.150/32")
.withIpProtocol("tcp")
.withFromPort(22)
.withToPort(22);
All the conditions that you specify in the IpPermission object must be met in order for ingress to
be allowed.
Specify the IP address using CIDR notation. If you specify the protocol as TCP/UDP, you must
provide a source port and a destination port.You can authorize ports only if you specify TCP or UDP.
2. Create and initialize an AuthorizeSecurityGroupIngressRequest instance. Use the withGroupName
method to specify the security group name, and pass the IpPermission object you initialized earlier
to the withIpPermissions method, as follows:
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest
=
new AuthorizeSecurityGroupIngressRequest();
authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup")
.withIpPermissions(ipPermission);
3. Pass the request object into the authorizeSecurityGroupIngress method, as follows:
amazonEC2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngress
Request);
If you call authorizeSecurityGroupIngress with IP addresses for which ingress is already
authorized, the method throws an exception. Create and initialize a new IpPermission object to
authorize ingress for different IPs, ports, and protocols before calling
AuthorizeSecurityGroupIngress.
Whenever you call the authorizeSecurityGroupIngress or authorizeSecurityGroupEgress methods,
a rule is added to your security group.
Version v1.0.0
28
AWS SDK for Java Developer Guide
Tutorial: Starting an EC2 Instance