我在负载均衡器后面有 2 个实例,我需要确保 /admin.php 脚本的访问安全,以便仅某些 IP 地址可以访问 尝试使用 WAF 执行此操作,但如果有更简单的方法使用 ALB 执行此操作,也可以
以下代码目前全球适用
resource "aws_wafv2_ip_set" "allowed_ips" {
name = "allowed-ips"
scope = "REGIONAL"
description = "IP set containing allowed IP addresses"
ip_address_version = "IPV4"
addresses = var.allowed_ip_addresses
}
resource "aws_wafv2_web_acl" "web_acl" {
name = "example-web-acl"
description = "Example Web ACL"
scope = "REGIONAL"
default_action {
block {}
}
visibility_config {
cloudwatch_metrics_enabled = false
metric_name = "web-acl-metric"
sampled_requests_enabled = false
}
rule {
name = "allow-only-from-allowed-ips"
priority = 1
statement {
ip_set_reference_statement {
arn = aws_wafv2_ip_set.allowed_ips.arn
}
}
action {
allow {}
}
visibility_config {
cloudwatch_metrics_enabled = false
metric_name = "allow-only-from-allowed-ips-metric"
sampled_requests_enabled = false
}
}
}
resource "aws_wafv2_web_acl_association" "load_balancer_acl_association" {
resource_arn = aws_lb.external_alb.arn
web_acl_arn = aws_wafv2_web_acl.web_acl.arn
}
如果需要管理的 IP 数量较少,您可以使用 ALB 侦听器规则来执行此操作。您最多可以提及 4 个源 IP,因为条件总数为 5。
下面是一个粗略的示例:
resource "aws_lb_listener_rule" "static" {
listener_arn = aws_lb_listener.front_end.arn
priority = 100
action {
type = "forward"
target_group_arn = aws_lb_target_group.static.arn
}
condition {
path_pattern {
values = ["/admin.php"]
}
}
condition {
source_ip {
values = ["1.2.3.4/32"]
}
}
}
resource "aws_lb_listener_rule" "static" {
listener_arn = aws_lb_listener.front_end.arn
priority = 101
action {
type = "forward"
target_group_arn = aws_lb_target_group.static.arn
}
condition {
path_pattern {
values = ["/admin.php"]
}
}
action {
type = "fixed-response"
fixed_response {
content_type = "text/plain"
message_body = "Access Denies"
status_code = "403"
}
}
优先级为100的规则是允许IP列表(即转发到相应的目标组)。规则 101 将为其他所有人返回
fixed-response
403。