I am trying to create a resource using terraform.
My resource now is:
resource "aws_cloudwatch_event_rule" "vm-rule-ec2" {
name = "${var.env_prefix}-vm-rule-ec2-state"
description = "EC2 instance changing state"
event_pattern = <<EOF
{
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"],
"detail": {
"state": ["stopping", "pending"],
"instance-id": ["i-01234567891112"]
}
}
EOF
}
I want to create it and the instance id to be fetched from aws, like when i am creating the ec2 instance with aws_instance resource.
Any ideas?
I tried some methods like this:
data "aws_instances" "vm" {
filter {
name = "tag:vm"
values = ["vm"]
}
}
resource "aws_cloudwatch_event_rule" "vm-rule-ec2" {
for_each = data.aws_instances.vm.ids
name = "${var.env_prefix}-vm-rule-ec2-state-${each.key}"
description = "EC2 instance changing state"
event_pattern = jsonencode({
source = ["aws.ec2"]
detail_type = ["EC2 Instance State-change Notification"]
detail = {
state = ["stopping", "pending"]
"instance-id" = ["${each.value}"]
}
})
}