如何通过Terraform配置EC2安全组,指定公网IP及Kibana实例访问Elasticsearch
解决Elasticsearch安全组配置问题:限制特定IP访问并允许集群通信
正确配置思路
- 拆分Ingress规则,避免同一规则混合多种访问来源
- 针对SSH访问,仅开放给你的IP地址
- 针对Elasticsearch 9200端口,同时开放给你的IP和Kibana实例的IP(同VPC场景优先用私有IP,更安全)
- 针对集群内部通信(9200-9300端口),使用
self = true允许同一安全组内的实例互相访问
修正后的Terraform配置
resource "aws_security_group" "elasticsearch_sg" { vpc_id = aws_vpc.elastic_vpc.id # 允许你的IP访问SSH(22端口) ingress { description = "Allow SSH from my IP" cidr_blocks = [var.access_ip] # 格式为 x.x.x.x/32 from_port = 22 protocol = "tcp" to_port = 22 } # 允许你的IP访问Elasticsearch 9200端口 ingress { description = "Allow Elasticsearch 9200 from my IP" cidr_blocks = [var.access_ip] from_port = 9200 protocol = "tcp" to_port = 9200 } # 允许Kibana实例访问Elasticsearch 9200端口(同VPC用私有IP) ingress { description = "Allow Elasticsearch 9200 from Kibana instance" cidr_blocks = ["${aws_instance.kibana.private_ip}/32"] from_port = 9200 protocol = "tcp" to_port = 9200 } # 允许Elasticsearch集群内部节点通信(9200-9300端口) ingress { description = "Allow Elasticsearch cluster internal communication" self = true from_port = 9200 protocol = "tcp" to_port = 9300 } egress { description = "Allow all outbound traffic" cidr_blocks = ["0.0.0.0/0"] from_port = 0 protocol = "-1" to_port = 0 } tags = { Name = "elasticsearch_sg" } }
关键配置说明
- 规则拆分:把不同来源、不同端口的访问规则拆分成独立Ingress块,避免逻辑混淆,便于维护排查。
- Kibana IP引用:用Terraform插值语法
${aws_instance.kibana.private_ip}/32直接引用Kibana实例的私有IP;若需用公网IP,替换为public_ip即可。 - 集群内部通信:
self = true会让所有关联此安全组的Elasticsearch实例互相访问9200-9300端口,满足集群节点发现、数据同步需求。 - 端口精准控制:9200作为对外访问端口仅开放给指定IP,9300仅用于集群内部,遵循最小权限原则。
内容的提问来源于stack exchange,提问作者Temo Hatna
相关产品推荐
相关产品推荐

