I am given a task to create the similar ec2 instance from existing ec2 instance from the infrastructure in AWS. Is there any way I can import all the setting from existing ec2 and create similar ec2 having the same attributes like vpc, security group, volume type, size and user data.
3 Answers
1
votes
You would use the aws_instance
data source to get a reference to the existing instance in your Terraform, after which you could create a new one using the aws_instance
resource, passing all the values from the data source.
0
votes
You can use this example code. Enter the instance id which you want to clone
variable "AWS_ACCESS_KEY" {}
variable "AWS_SECRET_KEY" {}
variable "AWS_REGION" {}
variable "AWS_INSTANCE_ID" {
description = "The instance id which you want to copy"
}
provider "aws" {
access_key = "${var.AWS_ACCESS_KEY}"
secret_key = "${var.AWS_SECRET_KEY}"
region = "${var.AWS_REGION}"
}
data "aws_instance" "my_ec2" {
instance_id = "${var.aws_instance_id}"
}
output "instance_id" {
value = "${data.aws_instance.my_ec2.id}"
}
resource "aws_instance" "new_instance" {
ami = "${data.aws_instance.my_ec2.ami}"
instance_type = "${data.aws_instance.my_ec2.instance_type}"
subnet_id = "${data.aws_instance.my_ec2.subnet_id}"
security_groups = "${data.aws_instance.my_ec2.security_groups}"
}