Importing AWS Instances using Terraform

Hello Team,

I have a request from my customer to manage the existing VM’s through terraform. The existing VM’s are launched manually. I was able to import one single vm, for which a tfstate file is created.

I want to know how do I import multiple vm’s ? since we have just one tf state file. Do I need to create separate ec2.tf for each instances ? Please clarify?

Also would like to know what are the other things do we need to import apart from aws instance ?

Security groups ?

Volume/Volume attachment ?

VPC?

DNS?

Appreciate any suggestions – Thanks.

You will need to import whatever resources you want to manage via Terraform, so yes you might want VPCs, SGs, Route53, etc.

With regard to the code there are lots of different ways to structure things. You could have totally different EC2 resources, which works well when they are very different from each other. You could also use count or for_each to have multiple copies of the same resource - that works best when the different resources are very similar and in some way related, count being best for instances treated as “cattle” instead of “pets”.

You might also want to split things into multiple root modules/state files. For example, you might want the core networking (e.g. VPC) to be separated from instances. It really depends ho things are wanting to be managed.

ThankYou for your response.
Would you mind confirming if Key_pair gets imported while we import ec2 instance ?

I imported key_pairs separately and when I run terraform plan, it throws an error below. Can someone please assist?

PS C:\Users\avinash.yadav\Desktop\terraform-import> .\terraform.exe plan

│ Error: Missing required argument

│ on ec2.tf line 631, in resource “aws_key_pair” “key_management”:
│ 631: resource “aws_key_pair” “key_management” {

│ The argument “public_key” is required, but no definition was found.

I have attached the code for your reference.
key_pair.txt (1.7 KB)