I have terraform code which deploys ec2 and reuses Elastic IPs without distroying.
Now I have new EIP which is migrated from different account, I want use that IP instead of EIP in current deployment.
Current working code
<code>resource "aws_eip" "main" {
count = var.num_instances
vpc = true
tags = merge(
local.tags,
{
"Name" = "${count.index + 1}-${var.env_name}-${var.region}",
},
)
lifecycle {
prevent_destroy = true
}
}
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
allocation_id = aws_eip.main[count.index].id
lifecycle {
create_before_destroy = true
}
}
</code>
<code>resource "aws_eip" "main" {
count = var.num_instances
vpc = true
tags = merge(
local.tags,
{
"Name" = "${count.index + 1}-${var.env_name}-${var.region}",
},
)
lifecycle {
prevent_destroy = true
}
}
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
allocation_id = aws_eip.main[count.index].id
lifecycle {
create_before_destroy = true
}
}
</code>
resource "aws_eip" "main" {
count = var.num_instances
vpc = true
tags = merge(
local.tags,
{
"Name" = "${count.index + 1}-${var.env_name}-${var.region}",
},
)
lifecycle {
prevent_destroy = true
}
}
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
allocation_id = aws_eip.main[count.index].id
lifecycle {
create_before_destroy = true
}
}
I tried to get list of IPs and tried to reuse but it does not work
<code>+ data "aws_eip" "existing_eips" {
+ filter {
+ name = "tag:Team"
+ values = ["myteam"]
+ }
+ }
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
- allocation_id = aws_eip.main[count.index].id
+ allocation_id = data.aws_eip.existing_eips.id[count.index]
lifecycle {
create_before_destroy = true
}
}
</code>
<code>+ data "aws_eip" "existing_eips" {
+ filter {
+ name = "tag:Team"
+ values = ["myteam"]
+ }
+ }
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
- allocation_id = aws_eip.main[count.index].id
+ allocation_id = data.aws_eip.existing_eips.id[count.index]
lifecycle {
create_before_destroy = true
}
}
</code>
+ data "aws_eip" "existing_eips" {
+ filter {
+ name = "tag:Team"
+ values = ["myteam"]
+ }
+ }
resource "aws_eip_association" "main" {
count = var.num_instances
instance_id = aws_instance.main[count.index].id
- allocation_id = aws_eip.main[count.index].id
+ allocation_id = data.aws_eip.existing_eips.id[count.index]
lifecycle {
create_before_destroy = true
}
}
What is standard way to do this, I don’t want to play with state file.
Thanks in advance.