Hôm nay mình gặp khá nhiều lỗi trong khi cố gắng add thêm 1 rule trong Sec Group của AWS bằng terraform.
Đầu tiên mình đã có sẵn 1 SecGroup template đã được sử dụng trước đó.
resource "aws_security_group" "msk-sg" {
name = "msk-sg"
vpc_id = data.terraform_remote_state.network.outputs.vpc_id
ingress = [
{
cidr_blocks = [data.terraform_remote_state.network.outputs.vpc_cidr_block]
description = "Allow Integration Nim subnets"
ipv6_cidr_blocks = []
from_port = 9094
to_port = 9094
protocol = "tcp"
prefix_list_ids = []
security_groups = []
self = true
},
Bạn có thể thấy là mình đang có 1 rule inbound vào port 9094 cho phép subnet được lấy từ data.terraform_remote_state.network.outputs.vpc_cidr_block
vì để 1 decription khác nên là mình đã copy thành

Khi mình run terraform apply thì bị lỗi.
Plan: 0 to add, 1 to change, 0 to destroy.
aws_security_group.msk-sg: Modifying... [id=sg-01b00f8cf9112f8f8]
╷
│ Error: updating Security Group (sg-01b00f8cf9112f8f8) ingress rules: authorizing Security Group (ingress) rules: InvalidPermission.Duplicate: the specified rule "peer: sg-01b00f8cf9112f8f8, TCP, from port: 9094, to port: 9094, ALLOW" already exists
│ status code: 400, request id: d87f73d8-ee17-40f0-9840-a6f1b99d5097
│
│ with aws_security_group.msk-sg,
│ on c3-02-msk-secgroup.tf line 10, in resource "aws_security_group" "msk-sg":
│ 10: resource "aws_security_group" "msk-sg" {
│
╵

Thì lúc này mình dò lại doc:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group
Bạn có thể thấy là sau ingress không phải là 1 array

Vậy giờ chúng ta có 2 cách:
với array: thì bạn add thêm subnet vào cidr_blocks và chấp nhận là không thể đánh description cho từng subnet.
resource "aws_security_group" "msk-sg" {
name = "msk-sg"
vpc_id = data.terraform_remote_state.network.outputs.vpc_id
ingress = [
{
cidr_blocks = [data.terraform_remote_state.network.outputs.vpc_cidr_block,"192.168.1.0"]
description = "Allow Integration Nim subnets"
ipv6_cidr_blocks = []
from_port = 9094
to_port = 9094
protocol = "tcp"
prefix_list_ids = []
security_groups = []
self = true
},
Nếu bạn muốn add thêm subnet và cũng muốn description riêng
resource "aws_security_group" "allow_tls" {
name = "allow_tls"
description = "Allow TLS inbound traffic"
vpc_id = aws_vpc.main.id
ingress {
description = "TLS from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [aws_vpc.main.cidr_block]
}
ingress {
description = "Allow Integration Nim subnets"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["192.168.1.0"]
}