This topic describes how to use Alibaba Cloud SDK for Java to update security group rules.

Prerequisites

Before you begin, ensure that the following requirements are met:
  • You must have an Alibaba Cloud account and an AccessKey pair (AccessKey ID and AccessKey secret) to use Alibaba Cloud SDK for Java. You can create and view your AccessKey pair on the AccessKey Management page in the Alibaba Cloud Management Console.
  • You have installed Alibaba Cloud SDK for Java. For more information about SDK versions, see Alibaba Cloud SDK.
    <dependencies>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.4</version>
        </dependency>
    </dependencies>

Sample code

This section shows the sample request code:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.util.List;

/**
 * This topic involves the following API operations:
 * DescribeSecurityGroups    Queries the basic information of the security groups that you created.
 * DescribeSecurityGroupAttribute    Queries the details of a security group.
 * AuthorizeSecurityGroup    Creates an inbound security group rule.
 * RevokeSecurityGroup    Deletes an inbound security group rule.
 */
public class UpdataSecurityGroup {

    public static void main(String[] args) {
        // Initialize common request parameters.
        IAcsClient client = Initialization();
        // Query the basic information of security groups.
        List<DescribeSecurityGroupsResponse.SecurityGroup> securityGroups = DescribeSecurityGroups(client);
        if (securityGroups.size() ! = 0) {
            // Query the security groups that you need.
            DescribeSecurityGroupsResponse.SecurityGroup securityGroup = securityGroups.get(0);
            String securityGroupId = securityGroup.getSecurityGroupId();
            // Query the details of a security group.
            DescribeSecurityGroupAttribute(client, securityGroupId);
            // Create an inbound security group rule.
            AuthorizeSecurityGroup(securityGroupId, client);
            // Delete an inbound security group rule.
            RevokeSecurityGroup(client, securityGroupId);
        }
    }

    /**
     * RevokeSecurityGroup    Deletes an inbound security group rule.
     * To precisely locate and delete a security group rule, you must specify the following parameters:
     * IpProtocol, PortRange, SourcePortRange (optional), NicType, Policy, DestCidrIp, and SourceCidrIp (optional).
     */
    private static void RevokeSecurityGroup(IAcsClient client, String securityGroupId) {
        RevokeSecurityGroupRequest request = new RevokeSecurityGroupRequest();
        // The transport layer protocol. The values are case-sensitive. Valid values:
        // icmp
        // gre
        // tcp
        // udp
        // all: supports all protocols.
        request.setIpProtocol("udp");
        // The range of the target port numbers relevant to the transport layer protocols. Valid values:
        // When the IpProtocol parameter is set to tcp or udp, the port range is 1 to 65535. Separate the start port number and the end port number with a forward slash (/). Correct example: 1/200. Incorrect example: 200/1.
        // When the IpProtocol parameter is set to icmp, the port range is -1/-1, indicating all ports.
        // When the IpProtocol parameter is set to gre, the port range is -1/-1, indicating all ports.
        // When the IpProtocol parameter is set to all, the port range is -1/-1, indicating all ports.
        request.setPortRange("1/200");
        // The network interface card (NIC) type. Valid values:
        // internet: Internet NIC
        // intranet: Intranet NIC
        // If SourceGroupId is specified but SourceCidrIp is not, NicType must be set to intranet. Default value: internet.
        request.setNicType("intranet");
        // The access policy. Valid values:
        // accept: grants access.
        // drop: denies access without returning a rejection response.
        // Default value: accept.
        request.setPolicy("accept");
        // The range of destination IP addresses. Classless Inter-Domain Routing (CIDR) blocks and IPv4 addresses are supported. Default value: 0.0.0.0/0.
        request.setDestCidrIp("127.30.XX.XX");
        // The range of source IP addresses. CIDR blocks and IPv4 addresses are supported. Default value: 0.0.0.0/0.
        request.setSourceCidrIp("10.X.X.X");
        // The ID of the destination security group.
        request.setSecurityGroupId(securityGroupId);
        try {
            RevokeSecurityGroupResponse response = client.getAcsResponse(request);
            System.out.println("--------------------The inbound security group is deleted.--------------------");
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }

    /**
     * Create an inbound security group rule.
     */
    private static void AuthorizeSecurityGroup(String securityGroupId, IAcsClient client) {
        AuthorizeSecurityGroupRequest request = new AuthorizeSecurityGroupRequest();
        // The ID of the target security group.
        request.setSecurityGroupId(securityGroupId);
        // The transport layer protocol. The values are case-sensitive. Valid values: tcp, udp, icmp, gre, and all. Value all indicates that all protocols are supported.
        request.setIpProtocol("udp");
        // The range of the target port numbers relevant to the transport layer protocols. Valid values:
        // When the IpProtocol parameter is set to tcp or udp, the port range is 1 to 65535. Separate the start port number and the end port number with a forward slash (/). Correct example: 1/200. Incorrect example: 200/1.
        // When the IpProtocol parameter is set to icmp, the port range is -1/-1, indicating all ports.
        // When the IpProtocol parameter is set to gre, the port range is -1/-1, indicating all ports.
        // When the IpProtocol parameter is set to all, the port range is -1/-1, indicating all ports.
        request.setPortRange("1/200");
        // The network interface card (NIC) type. Valid values:
        // internet: Internet NIC.
        // intranet: Intranet NIC.
        request.setNicType("intranet");
        // Configure the access policy. Valid values:
        // accept (default): grants access.
        // drop: denies access without returning a rejection response.
        request.setPolicy("accept");
        // The priority of the security group rule. Valid values: 1 to 100.
        request.setPriority("1");
        // The range of source IPv4 addresses. CIDR blocks and IPv4 addresses are supported.
        // The ID of the source security group for which you want to configure the access policy. You must specify at least one of the SourceGroupId and SourceCidrIp parameters.
        // If SourceGroupId is specified but SourceCidrIp is not, NicType must be set to intranet.
        // If both SourceGroupId and SourceCidrIp are specified, SourceCidrIp takes precedence.
        request.setSourceCidrIp("10.X.X.X");
        try {
            AuthorizeSecurityGroupResponse response = client.getAcsResponse(request);
            System.out.println("-------------------- The inbound security group was created. --------------------");
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }

    /**
     * Query the details of a security group.
     */
    private static void DescribeSecurityGroupAttribute(IAcsClient client, String securityGroupId) {
        DescribeSecurityGroupAttributeRequest request = new DescribeSecurityGroupAttributeRequest();
        request.setSecurityGroupId(securityGroupId);
        // The NIC type. Valid values:
        // internet: Internet NIC.
        // intranet: Intranet NIC.
        // Default value: internet.
        request.setNicType("internet");
        // The direction in which a security group rule is applied. Valid values:
        // egress: outbound
        // ingress: inbound
        // all: direction-insensitive
        // Default value: all.
        request.setDirection("ingress");
        try {
            DescribeSecurityGroupAttributeResponse response = client.getAcsResponse(request);
            System.out.println("--------------------The details of the security group were queried.--------------------");
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }

    }

    /**
     * DescribeSecurityGroups    Queries the basic information of the security groups that you created.
     */
    private static List<DescribeSecurityGroupsResponse.SecurityGroup> DescribeSecurityGroups(IAcsClient client) {
        DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
        // The network type.
        request.setNetworkType("vpc");
        // The security group name.
        request.setSecurityGroupName("sg-bp168k8XXXXX");
        try {
            DescribeSecurityGroupsResponse response = client.getAcsResponse(request);
            List<DescribeSecurityGroupsResponse.SecurityGroup> securityGroups = response.getSecurityGroups();
            System.out.println("--------------------The security groups were queried.--------------------");
            System.out.println(new Gson().toJson(response));
            return securityGroups;
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new RuntimeException();
        }
    }

    /**
     * Initialization  Initializes common request parameters.
     */
    private static IAcsClient Initialization() {
        // Initialize request parameters.
        DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>", // The ID of the region.
                "<your-access-key-id>", // The AccessKey ID.
                "<your-access-key-secret>"); // The AccessKey secret.
        return new DefaultAcsClient(profile);
    }
}

Output

This section shows the sample success response:
--------------------The security groups were queried.--------------------
{
    "requestId": "4D1E9065-C874-451D-9FC0-CD37CEA125EC", 
    "regionId": "cn-hangzhou", 
    "totalCount": 1, 
    "pageNumber": 1, 
    "pageSize": 10, 
    "securityGroups": [
        {
            "securityGroupId": "sg-bp168k8dwrx9b7c5b483", 
            "description": "System created security group.", 
            "securityGroupName": "sg-bp168k8XXXXX", 
            "vpcId": "vpc-bp1m7vXXXXXX", 
            "creationTime": "2019-04-08T00:07:28Z", 
            "resourceGroupId": "", 
            "tags": [...]
        }
    ]
}
--------------------The details of the security group were queried.--------------------
{
    "requestId": "D8894C74-1779-4DF4-A272-792D14DF25AE", 
    "regionId": "cn-hangzhou", 
    "securityGroupId": "sg-bp168k8XXXXX", 
    "description": "System created security group.", 
    "securityGroupName": "sg-bp168kXXXXX", 
    "vpcId": "vpc-bp1m7vXXXXX", 
    "innerAccessPolicy": "Accept", 
    "permissions": [
        {
            "ipProtocol": "TCP", 
            "portRange": "22/22", 
            "sourcePortRange": "", 
            "sourceGroupId": "sg-bp156XXXXX", 
            "sourceGroupName": "TEST", 
            "sourceCidrIp": "", 
            "policy": "Accept", 
            "nicType": "intranet", 
            "sourceGroupOwnerAccount": "", 
            "destGroupId": "", 
            "destGroupName": "", 
            "destCidrIp": "", 
            "destGroupOwnerAccount": "", 
            "priority": "1", 
            "direction": "ingress", 
            "description": "XXXXXX", 
            "createTime": "2019-08-16T05:20:48Z"
        }, 
        {
            "ipProtocol": "TCP", 
            "portRange": "80/80", 
            "sourcePortRange": "", 
            "sourceGroupId": "sg-bp156XXXXX", 
            "sourceGroupName": "TEST", 
            "sourceCidrIp": "", 
            "policy": "Accept", 
            "nicType": "intranet", 
            "sourceGroupOwnerAccount": "", 
            "destGroupId": "", 
            "destGroupName": "", 
            "destCidrIp": "", 
            "destGroupOwnerAccount": "", 
            "priority": "1", 
            "direction": "ingress", 
            "description": "XXXXXX", 
            "createTime": "2019-08-10T07:22:01Z"
        }
    ]
}
--------------------The inbound security group was created.--------------------
{"requestId":"4ECA3CEF-E2F7-41A3-A5E6-6DF000572072"}
--------------------The inbound security group was deleted.--------------------
{"requestId":"4ECA3CEF-E2F7-41A3-A5E6-6DF000572072"}