本教程详细介绍如何使用Alibaba Cloud SDK for Java增加安全组规则,包括查看安全组详情。

前提条件

在使用本教程之前,请确保已完成以下操作:

  • 使用ECS管理控制台或通过API获取您需要的安全组ID,API接口请参见DescribeSecurityGroups
  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见 阿里云开发工具包(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>

代码示例

package cn.alibaba.sdk;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

import java.util.List;

/**
 * DescribeRegions    查询您可以使用的阿里云地域
 * DescribeSecurityGroupAttribute    查询一个安全组的详情
 * AuthorizeSecurityGroup    增加一条安全组入方向规则
 */
public class TestSecurityGroup {

    // 安全组ID(请自行配置)
    private static String SecurityGroupId = "sg-bp1fvm4xxxxx";

    public static void main(String[] args) {
        IAcsClient client = Initialization();
        // 查询可以使用的阿里云地域
        List<DescribeRegionsResponse.Region> regions = DescribeRegions(client);
        // 这里取集合的第一个元素(请按照您的实际需求进行选取)
        String regionId = regions.get(0).getRegionId();
        // 查询安全组的详情
        String securityGroupId = DescribeSecurityGroupAttribute(client, SecurityGroupId);
        // 修改安全组入方向规则
        AuthorizeSecurityGroup(securityGroupId, client);
    }

    /**
     * AuthorizeSecurityGroup    增加一条安全组入方向规则
     */
    private static void AuthorizeSecurityGroup(String securityGroupId, IAcsClient client) {
        AuthorizeSecurityGroupRequest request = new AuthorizeSecurityGroupRequest();
        // 目标安全组地域ID。
        // request.setRegionId(regionId);
        // 目标安全组ID。
        request.setSecurityGroupId(securityGroupId);
        // 传输层协议。取值大小写敏感。取值范围:tcp udp icmp gre all:支持所有协议。
        request.setIpProtocol("udp");
        // SecurityGroupId方开放的传输层协议相关的端口范围。取值范围。
        // TCP/UDP协议:取值范围为1~65535。使用斜线(/)隔开起始端口和终止端口。正确示范:1/200;错误示范:200/1。
        // ICMP协议:-1/-1。
        // GRE协议:-1/-1。
        // IpProtocol取值为all:-1/-1。
        request.setPortRange("1/200");
        // 网卡类型。取值范围:
        // internet:公网网卡。
        // intranet:内网网卡。
        request.setNicType("intranet");
        // 设置访问权限。取值范围:
        // accept(默认):接受访问。
        // drop:拒绝访问,不返回拒绝信息。
        request.setPolicy("accept");
        // 安全组规则优先级。取值范围:1~100。
        request.setPriority("1");
        // 源端IPv4 CIDR地址段。支持CIDR格式和IPv4格式的IP地址范围。
        // 需要设置访问权限的源端安全组ID。至少设置一项SourceGroupId或者SourceCidrIp参数。
        // 如果指定了SourceGroupId没有指定参数SourceCidrIp,则参数NicType取值只能为intranet。
        // 如果同时指定了SourceGroupId和SourceCidrIp,则默认以SourceCidrIp为准。
        request.setSourceCidrIp("10.0.0.0/8");
        try {
            AuthorizeSecurityGroupResponse response = client.getAcsResponse(request);
            System.out.println("--------------------入方向安全组新增成功--------------------");
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }

    /**
     * DescribeSecurityGroupAttribute    查询一个安全组的详情
     */
    private static String DescribeSecurityGroupAttribute(IAcsClient client, String securityGroupId) {
        DescribeSecurityGroupAttributeRequest request = new DescribeSecurityGroupAttributeRequest();
        request.setSecurityGroupId(securityGroupId);
        request.setDirection("all");
        try {
            DescribeSecurityGroupAttributeResponse response = client.getAcsResponse(request);
            System.out.println("--------------------安全组的详情查询成功--------------------");
            System.out.println(new Gson().toJson(response));
            return response.getSecurityGroupId();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }


    /**
     * DescribeRegions    查询您可以使用的阿里云地域
     */
    private static List<DescribeRegionsResponse.Region> DescribeRegions(IAcsClient client) {
        DescribeRegionsRequest request = new DescribeRegionsRequest();
        try {
            DescribeRegionsResponse response = client.getAcsResponse(request);
            System.out.println("--------------------地域信息集合查询成功--------------------");
            System.out.println(new Gson().toJson(response.getRegions()));
            return response.getRegions();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }

    /**
     * Initialization  初始化请求参数
     */
    private static IAcsClient Initialization() {
        // 初始化请求参数
        DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>",             // 您的可用区ID
                "<your-access-key-id>",         // 您的AccessKey ID
                "<your-access-key-secret>");    // 您的AccessKey Secret
        return new DefaultAcsClient(profile);
    }
}

执行结果

正确的返回结果类似如下:
[
    {
        "regionId": "cn-qingdao", 
        "localName": "华北 1", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "cn-beijing", 
        "localName": "华北 2", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "cn-zhangjiakou", 
        "localName": "华北 3", 
        "regionEndpoint": "ecs.cn-zhangjiakou.aliyuncs.com"
    }, 
    {
        "regionId": "cn-huhehaote", 
        "localName": "华北 5", 
        "regionEndpoint": "ecs.cn-huhehaote.aliyuncs.com"
    }, 
    {
        "regionId": "cn-hangzhou", 
        "localName": "华东 1", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "cn-shanghai", 
        "localName": "华东 2", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "cn-shenzhen", 
        "localName": "华南 1", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "cn-chengdu", 
        "localName": "西南1(成都)", 
        "regionEndpoint": "ecs.cn-chengdu.aliyuncs.com"
    }, 
    {
        "regionId": "cn-hongkong", 
        "localName": "香港", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "ap-northeast-1", 
        "localName": "亚太东北 1 (东京)", 
        "regionEndpoint": "ecs.ap-northeast-1.aliyuncs.com"
    }, 
    {
        "regionId": "ap-southeast-1", 
        "localName": "亚太东南 1 (新加坡)", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "ap-southeast-2", 
        "localName": "亚太东南 2 (悉尼)", 
        "regionEndpoint": "ecs.ap-southeast-2.aliyuncs.com"
    }, 
    {
        "regionId": "ap-southeast-3", 
        "localName": "亚太东南 3 (吉隆坡)", 
        "regionEndpoint": "ecs.ap-southeast-3.aliyuncs.com"
    }, 
    {
        "regionId": "ap-southeast-5", 
        "localName": "亚太东南 5 (雅加达)", 
        "regionEndpoint": "ecs.ap-southeast-5.aliyuncs.com"
    }, 
    {
        "regionId": "ap-south-1", 
        "localName": "亚太南部 1 (孟买)", 
        "regionEndpoint": "ecs.ap-south-1.aliyuncs.com"
    }, 
    {
        "regionId": "us-east-1", 
        "localName": "美国东部 1 (弗吉尼亚)", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "us-west-1", 
        "localName": "美国西部 1 (硅谷)", 
        "regionEndpoint": "ecs.aliyuncs.com"
    }, 
    {
        "regionId": "eu-west-1", 
        "localName": "英国 (伦敦)", 
        "regionEndpoint": "ecs.eu-west-1.aliyuncs.com"
    }, 
    {
        "regionId": "me-east-1", 
        "localName": "中东东部 1 (迪拜)", 
        "regionEndpoint": "ecs.me-east-1.aliyuncs.com"
    }, 
    {
        "regionId": "eu-central-1", 
        "localName": "欧洲中部 1 (法兰克福)", 
        "regionEndpoint": "ecs.eu-central-1.aliyuncs.com"
    }
]
--------------------安全组的详情查询成功--------------------
{
    "requestId": "01E0F0A6-E699-415F-B3E0-9A72B2D740AA", 
    "regionId": "cn-hangzhou", 
    "securityGroupId": "sg-bp1fvm49q1jfjsvopt69", 
    "description": "", 
    "securityGroupName": "k8s_sg", 
    "vpcId": "vpc-bp1gnu8br4ay7beb2wxl8", 
    "innerAccessPolicy": "Accept", 
    "permissions": [
        {
            "ipProtocol": "UDP", 
            "portRange": "1/200", 
            "sourcePortRange": "", 
            "sourceGroupId": "", 
            "sourceGroupName": "", 
            "sourceCidrIp": "10.0.0.0/8", 
            "policy": "Accept", 
            "nicType": "intranet", 
            "sourceGroupOwnerAccount": "", 
            "destGroupId": "", 
            "destGroupName": "", 
            "destCidrIp": "", 
            "destGroupOwnerAccount": "", 
            "priority": "1", 
            "direction": "ingress", 
            "description": "", 
            "createTime": "2019-09-16T03:34:17Z"
        } 
    ]
}
--------------------入方向安全组新增成功--------------------
{"requestId":"29BDA8FB-3BC3-42A8-B5F3-D2C9070B2124"}