繁体   English   中英

如何将 AWS Elastic IP 分配给具有 Terraform 的新创建的 EC2 实例,而不会在创建另一个实例时重新分配它?

[英]How to assign an AWS Elastic IP to a newly created EC2 instance with Terraform without it getting reassigned when another instance is created?

我目前有以下Terraform计划:

provider "aws" {
  region = var.region
}

resource "aws_instance" "ec2" {
  ami             = var.ami
  instance_type   = var.instanceType
  subnet_id       = var.subnet 
  security_groups = var.securityGroups 

  timeouts {
    create = "2h"
    delete = "2h"
  }

  tags = {
    Name = "${var.ec2ResourceName}"
    CoreInfra = "false"
  }

  lifecycle {
    prevent_destroy = true
  }

  key_name = "My_Key_Name"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    password    = ""
    private_key = file(var.keyPath)
    host        = self.public_ip
  }

  provisioner "file" {
    source      = "/home/ec2-user/code/backend/ec2/setup_script.sh"
    destination = "/tmp/setup_script.sh"
  }

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/setup_script.sh",
      "bash /tmp/setup_script.sh ${var.ec2ResourceName}"
    ]
  }
}

resource "aws_eip" "eip_manager" {
  name = "eip-${var.ec2ResourceName}"
  instance = aws_instance.ec2.id
  vpc = true
  
  tags = {
    Name = "eip-${var.ec2ResourceName}"
  }

  lifecycle {
    prevent_destroy = true
  }
}

该计划可以运行多次,每次创建一个 EC2 实例而不删除前一个实例。 但是,有一个 Elastic IP 最终被重新分配给最近创建的 EC2 实例。 如何将弹性 IP 添加到每个未重新分配的新实例?

也许与aws_eip_association ,这里是片段:

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.ec2.id
  allocation_id = aws_eip.eip_manager.id
}

更多信息: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip_association

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM