如何避免 RDS 实例和安全组的模块中出现循环错误

Ale*_*x G 1 amazon-web-services terraform

我正在编写一个 terraform 模块,该模块提供 RDS 数据库实例及其用于控制​​入站连接的关联安全组。我遇到的问题是安全组资源需要数据库端口作为参数,而数据库实例资源需要安全组 ID 作为参数。因此出现循环错误。

resource "aws_security_group" "this" {
  name = "${local.name}-inbound"
  description = "Allow inbound traffic from customer instances and management"
  vpc_id = "${var.vpc_id}"
  ingress {
    from_port = "${aws_db_instance.this.port}"
    to_port   = "${aws_db_instance.this.port}"
    protocol  = 6
    security_groups = ["${var.ingress_sg_ids}"]
  }
}

resource "aws_db_instance" "this" {
  allocated_storage       = "${var.storage_size}"
  storage_type            = "${var.storage_type}"
  engine                  = "${var.db_engine}"
  engine_version          = "${var.db_engine_version}"
  instance_class          = "${var.instance_type}"
  identifier_prefix       = "${local.name}-"
  name                    = "${var.env}_${var.workspace}"
  username                = "${var.root_username}"
  password                = "${random_id.root_password.b64}"
  db_subnet_group_name    = "${aws_db_subnet_group.this.name}"
  parameter_group_name    = "${var.param_group_name}"
  backup_retention_period = "${var.backup_retention_period}"
  copy_tags_to_snapshot   = true
  kms_key_id              = "${aws_kms_key.this.arn}"
  storage_encrypted       = true
  skip_final_snapshot     = "${var.skip_final_snapshot}"
  vpc_security_group_ids  = ["${aws_security_group.this.id}"]
}
Run Code Online (Sandbox Code Playgroud)

错误信息如下:

* Cycle: module.rds.aws_db_instance.this, module.rds.aws_security_group.this
Run Code Online (Sandbox Code Playgroud)

Iso*_*Iso 6

您存在循环依赖关系,因为您的实例取决于您的安全组,而安全组的内联规则又取决于您的实例。作为解决方法,您可以使用aws_security_group_rule资源:

resource "aws_security_group_rule" "db_ingress_sgr" {
  type                     = "ingress"
  security_group_id        = "${aws_security_group.this.id}"
  from_port                = "${aws_db_instance.this.port}"
  to_port                  = "${aws_db_instance.this.port}"
  protocol                 = 6
  source_security_group_id = "${var.ingress_sg_ids}"
}
Run Code Online (Sandbox Code Playgroud)

Terraform 将创建(空)安全组,然后创建您的 RDS 实例,然后创建安全组规则。

请注意source_security_group_id,这种方式一次只能定义一个,因此请检查ingress_sg_ids变量的类型。

注意(来自文档):

目前,您无法将具有内联规则的安全组与任何安全组规则资源结合使用。这样做会导致规则设置冲突并覆盖规则。