-1

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}"]
    }
  })
}
  • 1
    What error do you see? – Paolo May 12 '23 at 15:14
  • 1
    "I tried some methods like this"... and? What happened when you tried that? Did you get an error message? If so, edit your question to include the exact error message. Did it just give you a terraform plan output different than you expected? If so, edit your question to include that terraform plan output. – Mark B May 12 '23 at 15:42

1 Answers1

0

Not sure why EventBridge coming into picture if you want to fetch instance id of ec2 instance. You should try Terraform Output if you want to fetch ID of EC2 instance.

For example:

resource "aws_instance" "app_server" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"

  tags = {
    Name = var.instance_name
  }
}

    output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.app_server.id
}

Refer: https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-outputs

Vikas Banage
  • 494
  • 1
  • 8
  • 25