【问题标题】:How to assign multiple AWS Elastic IPs to a newly created EC2 instance with Terraform?如何使用 Terraform 将多个 AWS Elastic IP 分配给新创建的 EC2 实例?
【发布时间】:2021-06-03 07:24:19
【问题描述】:

使用 terraform,我需要将 3 个弹性 IP 添加到一个新的 EC2 实例。 terraform yml 将创建实例以及 EIP。

我已尝试按如下方式执行此操作:

resource "aws_eip" "server_dev1_eip1" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_eip" "server_dev1_eip2" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_eip" "server_dev1_eip3" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

以上是创建 EIP,但只是将一个 EIP 与实例关联。

请指教

【问题讨论】:

    标签: amazon-web-services amazon-ec2 terraform elastic-ip


    【解决方案1】:

    您不能将多个弹性 IP 分配给单个弹性网络接口 (ENI)。默认情况下,一个 EC2 实例只有一个 ENI。您需要将更多 ENI 附加到 EC2 实例,然后将弹性 IP 附加到 ENI。

    【讨论】:

    【解决方案2】:

    如何通过 Terraform 将多个 AWS Elastic IP 分配给新创建的多个 EC2 实例

    data "aws_ami" "amazon" {
      owners      = ["137112412989"]
      most_recent = true
      filter {
        name   = "name"
        values = ["amzn2-ami-kernel-5.10-hvm-2.0*"]
      }
    }
    

    main.tf

    module "ec2_instance" {
      source = "terraform-aws-modules/ec2-instance/aws"
    
      version                = "~> 3.0"
      for_each               = toset(var.ec2_name)
      name                   = each.key
      ami                    = data.aws_ami.amazon.id
      instance_type          = var.instance_type
      iam_instance_profile   = module.iam.name
      key_name               = "super-secret-ssh"
      monitoring             = false
      vpc_security_group_ids = [module.sg.id]
      subnet_id              = module.vpc.public_subnets[0]
      ebs_optimized          = true
    }
    
    module "aws_eip" {
      source   = "./modules/eip"
      for_each = toset(var.ec2_name)
      instance = module.ec2_instance[each.key].id
    }
    

    模块/eip

    resource "aws_eip" "eip" {
      instance = var.instance
      vpc      = true
    }
    

    变量.tf

    variable "ec2_name" {
      type    = list(string)
      default = ["one", "three" , "whatever"]
    }
    
    variable "instance_type" {
      type    = string
      default = t2.micro
    }
    

    将创建三个 EC2 实例,每个实例都有一个附加的 AWS 弹性 IP。

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2021-09-03
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多