## 创建防火墙 ## 1. 安全组是一种虚拟防火墙,具备状态检测和数据包过滤能力,用于在云端划分安全域。通过配置安全组规则,您可以控制安全组内ECS实例的入流量和出流量。 2. 您使用Xshell客户端远程连接Linux系统ECS实例时,当安全组检测到从公网或内网有SSH请求,会逐一检查入方向上安全组规则、发送请求的设备的IP地址是否已存在、优先级是为同类规则第一、授权策略是否为允许、22端口是否开启等。只有匹配到一条安全组规则允许放行该请求时,方才建立数据通信。下图为使用Xshell远程连接Linux系统ECS实例的规则匹配举例。 ![安全组](https://img.kancloud.cn/3f/34/3f34c6dd7cfd6e5ebf70e28fa59653bf_1097x306.png) 3. 代码 ``` resource "alicloud_security_group" "group" { name = "sc" description = "course security group" vpc_id = alicloud_vpc.vpc.id } resource "alicloud_security_group_rule" "allow_22" { # The type of rule being created. #Valid options are ingress (inbound) or egress (outbound). type = "ingress" # the protocol. Can be tcp, udp, icmp, gre or all. ip_protocol = "tcp" #Network type, can be either internet or intranet, #the default value is internet. nic_type = "intranet" # Authorization policy, can be either accept or drop, #the default value is accept policy = "accept" # the range of port numbers relevant to the IP protocol. Default to "-1/-1". When the protocol is tcp or udp, each side port number range from 1 to 65535 and '-1/-1' will be invalid. For example, 1/200 means that the range of the port numbers is 1-200. Other protocols' 'port_range' can only be "-1/-1", and other values will be invalid port_range = "22/22" # The target security group ID within the same region. security_group_id = alicloud_security_group.group.id # The target IP address range. The default value is 0.0.0.0/0 (which means no restriction will be applied). Other supported formats include 10.159.6.18/12. Only IPv4 is supported cidr_ip = "0.0.0.0/0" } ``` ## 网络acl ## 1. 网络访问控制列表(ACL)是 VPC 中的网络访问控制功能,可以将网络 ACL 与交换机进行关联,实现对一个或多个子网流量的访问控制。规则与安全组相似,用户可以对网络 ACL 的规则进行自主设置自定规则。网络 ACL 的规则是无状态的,设置入站规则允许某些请求后,需要同时设置相应的出站规则,否则可能会导致某些请求无法响应。 ![网络acl](https://img.kancloud.cn/08/29/082917c4a3a166ea7063df550c51d2b3_1280x720.png) ``` data "alicloud_zones" "default" { available_resource_creation = "VSwitch" } resource "alicloud_vpc" "default" { cidr_block = "172.16.0.0/12" vpc_name = "VpcConfig" } resource "alicloud_vswitch" "default" { vpc_id = alicloud_vpc.default.id vswitch_name = "vswitch" cidr_block = cidrsubnet(alicloud_vpc.default.cidr_block, 4, 4) zone_id = data.alicloud_zones.default.ids.0 } resource "alicloud_network_acl" "default" { vpc_id = alicloud_vpc.default.id network_acl_name = "network_acl" description = "network_acl" ingress_acl_entries { description = "tf-testacc" network_acl_entry_name = "tcp23" source_cidr_ip = "196.168.2.0/21" policy = "accept" port = "22/80" protocol = "tcp" } egress_acl_entries { description = "tf-testacc" network_acl_entry_name = "tcp23" destination_cidr_ip = "0.0.0.0/0" policy = "accept" port = "-1/-1" protocol = "all" } resources { resource_id = alicloud_vswitch.default.id resource_type = "VSwitch" } } ```