Terraform:无法在实例上创建云观察警报

时间:2018-05-27 16:33:39

标签: amazon-web-services amazon-ec2 terraform amazon-cloudwatch

我正在尝试按如下方式创建云观察警报:

module "superb_queue_api-a" {
  source = "../../Modules/Services"

  no_of_inst    = 1
  ami_id        = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"
  subnets       = "${data.terraform_remote_state.state_pull.prod-pvt-sub-a}"
  key           = "sup_queue_inst"
  sec-group     = ["${aws_security_group.ec2_sg.id}"]
  tp            = "${var.is_production ? true : false}"

  instance-name = "sup-queue-api-a"
}

resource "aws_cloudwatch_metric_alarm" "queue_1" {
  alarm_name          = "sup-queue-api-a"
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "1"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  period              = "120"
  statistic           = "Average"
  threshold           = "90"

  dimensions {
    InstanceId = "${module.superb_queue_api-a.ec2-instance}"
  }

  alarm_description = "This metric monitors ec2 cpu utilization"
  alarm_actions     = ["${var.terraform_elb_name}"]
}

我有以下模块来旋转实例

resource "aws_instance" "ec2_instances" {
  count = "${var.no_of_inst}"

  #count         = "${var.countt}"
  ami           = "${var.ami_id}"
  instance_type = "${var.instance_type}"

  #vpc_id        = "${var.vpc}"
  subnet_id = "${var.subnets}"
  key_name  = "${var.key}"

  vpc_security_group_ids  = ["${var.sec-group}"]
  disable_api_termination = "${var.tp}"

  root_block_device {
    volume_size = 100
    volume_type = "gp2"
  }

  tags {
    Name = "${var.instance-name}"
  }
}

output.tf具有以下内容

output "ec2-instance" {
  value = "${aws_instance.ec2_instances.*.id}"
}

output "private_ip" {
  value = "${aws_instance.ec2_instances.*.private_ip}"
}

我收到以下错误:

Error: Error running plan: 1 error(s) occurred:

* aws_cloudwatch_metric_alarm.queue_1: dimensions (InstanceId): '' expected type 'string', got unconvertible type '[]interface {}'

有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

问题是module.superb_queue_api-a.ec2-instance是一个数组,因为该模块正在创建多个实例,模块的输出是一个包含所有实例的ID的数组。

我已经调整了代码,因此它为每个实例创建了一个警报:

 resource "aws_cloudwatch_metric_alarm" "queue_1" {
  count  = "${length(module.superb_queue_api-a.ec2-instance)}"

  alarm_name          = "sup-queue-api-a-${module.superb_queue_api-a.ec2-instance[count.index]}"
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "1"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  period              = "120"
  statistic           = "Average"
  threshold           = "90"

  dimensions {
    InstanceId = "${module.superb_queue_api-a.ec2-instance[count.index]}"
  }

  alarm_description = "This metric monitors ec2 cpu utilization"
  alarm_actions     = ["${var.terraform_elb_name}"]
}