Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

terraform - How to assign private IP in multiple EC2 instance?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Based on your short question and on the tag saying "terraform", I think that you are looking for what is explained in the doc here https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance.

To set up an ec2 instance with some IPs you choose, you should create before an aws_network_interface that will be attached to it (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/network_interface).

Double-check that all the IPs you want are under the same aws_subnet (which is another terraform resource to be defined first)

EDIT

Let me try to add an example (i can't test it at the moment but it should be easily verified)

EXAMPLE:

I'll pick the values from the doc, and we assume that 3 IPs you have already chosen are 172.16.10.100, 172.16.10.101, 172.16.10.102. All of them are included in the subnet range.

resource "aws_vpc" "my_vpc" {
  cidr_block = "172.16.0.0/16"

  tags = {
    Name = "tf-example"
  }
}

resource "aws_subnet" "my_subnet" {
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = "172.16.10.0/24"
  availability_zone = "us-west-2a"

  tags = {
    Name = "tf-example"
  }
}

resource "aws_network_interface" "foo" {
  subnet_id   = aws_subnet.my_subnet.id
  private_ips = ["172.16.10.100", "172.16.10.101", "172.16.10.102"]

  tags = {
    Name = "primary_network_interface"
  }
}

resource "aws_instance" "foo" {
  ami           = "ami-005e54dee72cc1d00" # us-west-2
  instance_type = "t2.micro"

  network_interface {
    network_interface_id = aws_network_interface.foo.id
    device_index         = 0
  }

  credit_specification {
    cpu_credits = "unlimited"
  }
}

resource "aws_instance" "foo_first" {
  ami           = "ami-005e54dee72cc1d00" # us-west-2
  instance_type = "t2.micro"

  network_interface {
    network_interface_id = aws_network_interface.foo.id
    device_index         = 1
  }

  credit_specification {
    cpu_credits = "unlimited"
  }
}

resource "aws_instance" "foo_second" {
  ami           = "ami-005e54dee72cc1d00" # us-west-2
  instance_type = "t2.micro"

  network_interface {
    network_interface_id = aws_network_interface.foo.id
    device_index         = 2
  }

  credit_specification {
    cpu_credits = "unlimited"
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...