How to launch ECs in an existing VPC using Terraform

use*_*955 5 amazon-web-services terraform

I need to create several new EC2, RDS, etc.using Terraform, in an existing AWS VPC. and the existing subnet, security group, iam, etc. they are not created by Terraform. it is created manually.

I heard the right way is to use terraform import (it is correct?). To test how terraform import works, I first tested how to import an existing EC2 in stead of an existing VPC, Because I do not want to accidentally change anything In an exist VPC.

before running

terraform import aws_instance.example i-XXXXXXXXXX
Run Code Online (Sandbox Code Playgroud)

It looks like I need to create a very detailed EC2 resource in my ec2.tf file, such as:

resource "aws_instance" "example" {
  iam_instance_profile = XXXXXXXXXX
  instance_type = XXXXXXX
  ami = XXXXXXX
  tags {
    Name = XXXXX
    Department = XXXX
    ....
  }
} 
Run Code Online (Sandbox Code Playgroud)

if I just write:

resource "aws_instance" "example" {
}
Run Code Online (Sandbox Code Playgroud)

it showed I missed ami and instance type,

if I write:

resource "aws_instance" "example" {
  instance_type = XXXXXXX
  ami = XXXXXXX
}
Run Code Online (Sandbox Code Playgroud)

then running "terraform apply" will change tags of my existing EC2 to nothing, change iam profile to nothing.

I have not tried how to import existing vpc, subnet, security group yet. I am afraid if I try, I have to put a lot of information of the existing vpc, subnet, security group, etc. my system is complex.

is it expected that I need to indicate so many details in my terraform code? isn't there a way so that I just simply indicate the id of existing stuff like vpc's id, and my new stuff will be created based on the existing id? sth. like:

data "aws_subnet" "public" {
    id = XXXXXXX
}

resource "aws_instance" "example" {
  instance_type = "t2.micro"
  ami = "${var.master_ami}"
  ......
  subnet_id = "${aws_subnet.public.id}"
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ker 10

您可以在导入期间将资源主体保留为空白,但是一旦导入,则需要返回并填写特定的详细信息。您可以使用terraform show命令查看导入的资源,并填写所有资源详细信息,因此,当您尝试运行terraform plan时,它不应显示任何更改。

但是,要回答您的问题,是的,您可以使用现有资源而无需导入它们。只需创建一个变量文件,其中包含新资源所需的现有资源ID,然后就可以引用所需的ID。

因此,您可以拥有一个.vars文件,其中包含以下内容:

variable "ami_id" {
  description = "AMI ID"
  default = "ami-xxxxxxxx"
}

variable "subnet_prv1" {
  description = "Private Subnet 1"
  default = "subnet-xxxxxx"
}
Run Code Online (Sandbox Code Playgroud)

然后在main.tf中创建资源:

resource "aws_instance" "example" {
   instance_type = "t2.micro"
   ami = "${var.ami_id}"
   ......
   subnet_id = "${var.subnet_prv1}"
}
Run Code Online (Sandbox Code Playgroud)

只是一种解决方法。还有其他一些,您可以在terraform文档中阅读这些变量

  • 谢谢瑞克。有用。所以总而言之,如果我需要使用 terraform 更改现有的 vpc(手动创建),我应该先导入,但如果我想从现有的 vpc 创建新组件,那么我将使用您发布的第二个解决方案。谢谢。 (2认同)