Terraform Import Module with Examples

Terraform Import Module with Examples

we know that terraform will provision the infrastructure in the form code and it will support multiple clouds like aws, azure.. There are times, we have to import the existing infrastructure into terraform code. Terraform giving the import functionality to migrate the manually created infrastructure into terraform. Terraform import command is used to import existing infrastructure. This command can only import only one resources at a time. We have to run multiple times to import multiple resources.

Terraform manages the infrastructure only created by it. It will not look after infrastructure created by some other procedure or manually. In this post we will see how to import manually created ec2 instance infrastructure into terraform code.

Terraform import Ec2 instance

lets create an ec2 instance manually using aws console

terraform import

Create an empty resource file for Ec2

To import an existing ec2 resource, first we have to create an empty resource block. lets create resource file to import ec2 instance. In the below code section you can see how resource block ec2 looks like.

cat myresource.tf

resource "aws_instance" "myec2example" {
}

Run Terraform import Command

Now run terraform import command to import ec2 instance. syntax of terraform import module command is

terraform    import    resource.name     id_of_resource_in_aws

root@ip-172-31-37-35:~/terraform# terraform import aws_instance.myec2example i-01b3cb06d57851fe8

aws_instance.myec2example: Importing from ID "i-01b3cb06d57851fe8"...
aws_instance.myec2example: Import prepared!
  Prepared aws_instance for import
aws_instance.myec2example: Refreshing state... [id=i-01b3cb06d57851fe8]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

Here id is ec2 instance id in aws which is created manually. After running import command ec2 will be imported into resource myec2example. 

after importing terraform.tfstate file will be created.

root@ip-172-31-37-35:~/terraform# ls -ltr

total 12
-rw-r--r-- 1 root root  133 Nov  8 02:08 provider.tf
-rw-r--r-- 1 root root   43 Nov  8 10:19 myresource.tf
-rw-r--r-- 1 root root 3314 Nov  8 10:19 terraform.tfstate

Lets check terraform.tfstate file.

root@ip-172-31-37-35:~/terraform# cat terraform.tfstate

{
  "version": 4,
  "terraform_version": "0.12.18",
  "serial": 1,
  "lineage": "bac49db9-4bce-62c0-6b38-b63d1c09d07d",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_instance",
      "name": "myec2example",
      "provider": "provider.aws",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "ami": "ami-0dba2cb6798deb6d8",
            "arn": "arn:aws:ec2:us-east-1:787645912603:instance/i-01b3cb06d57851fe8",
            "associate_public_ip_address": true,
            "availability_zone": "us-east-1e",
            "cpu_core_count": 1,
            "cpu_threads_per_core": 1,
            "credit_specification": [
              {
                "cpu_credits": "standard"
              }
            ],
            "disable_api_termination": false,
            "ebs_block_device": [],
            "ebs_optimized": false,
            "ephemeral_block_device": [],
            "get_password_data": false,
            "hibernation": false,
            "host_id": null,
            "iam_instance_profile": "",
            "id": "i-01b3cb06d57851fe8",
            "instance_initiated_shutdown_behavior": null,
            "instance_state": "running",
            "instance_type": "t2.micro",
            "ipv6_address_count": 0,
            "ipv6_addresses": [],
            "key_name": "",
            "metadata_options": [
              {
                "http_endpoint": "enabled",
                "http_put_response_hop_limit": 1,
                "http_tokens": "optional"
              }
            ],
            "monitoring": false,
            "network_interface": [],
            "outpost_arn": "",
            "password_data": "",
            "placement_group": "",
            "primary_network_interface_id": "eni-0a1b675376634d878",
            "private_dns": "ip-172-31-57-0.ec2.internal",
            "private_ip": "172.31.57.0",
            "public_dns": "ec2-54-87-181-81.compute-1.amazonaws.com",
            "public_ip": "54.87.181.81",
            "root_block_device": [
              {
                "delete_on_termination": true,
                "device_name": "/dev/sda1",
                "encrypted": false,
                "iops": 100,
                "kms_key_id": "",
                "volume_id": "vol-048212ad297402dcb",
                "volume_size": 8,
                "volume_type": "gp2"
              }
            ],
            "secondary_private_ips": [],
            "security_groups": [
              "launch-wizard-45"
            ],
            "source_dest_check": true,
            "subnet_id": "subnet-2cd44f12",
            "tags": {
              "Name": "terraformec2"
            },
            "tenancy": "default",
            "timeouts": {
              "create": null,
              "delete": null,
              "update": null
            },
            "user_data": null,
            "user_data_base64": null,
            "volume_tags": {},
            "vpc_security_group_ids": [
              "sg-0604857e6da455033"
            ]
          },
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo2MDAwMDAwMDAwMDAsImRlbGV0ZSI6MTIwMDAwMDAwMDAwMCwidXBkYXRlIjo2MDAwMDAwMDAwMDB9LCJzY2hlbWFfdmVyc2lvbiI6IjEifQ=="
        }
      ]
    }
  ]
}

terraform show command will show you imported ec2 instance.

root@ip-172-31-37-35:~/terraform# terraform show

# aws_instance.myec2example:
resource "aws_instance" "myec2example" {
    ami                          = "ami-0dba2cb6798deb6d8"
    arn                          = "arn:aws:ec2:us-east-1:787645912603:instance/i-01b3cb06d57851fe8"
    associate_public_ip_address  = true
    availability_zone            = "us-east-1e"
    cpu_core_count               = 1
    cpu_threads_per_core         = 1
    disable_api_termination      = false
    ebs_optimized                = false
    get_password_data            = false
    hibernation                  = false
    id                           = "i-01b3cb06d57851fe8"
    instance_state               = "running"
    instance_type                = "t2.micro"
    ipv6_address_count           = 0
    ipv6_addresses               = []
    monitoring                   = false
    primary_network_interface_id = "eni-0a1b675376634d878"
    private_dns                  = "ip-172-31-57-0.ec2.internal"
    private_ip                   = "172.31.57.0"
    public_dns                   = "ec2-54-87-181-81.compute-1.amazonaws.com"
    public_ip                    = "54.87.181.81"
    secondary_private_ips        = []
    security_groups              = [
        "launch-wizard-45",
    ]
    source_dest_check            = true
    subnet_id                    = "subnet-2cd44f12"
    tags                         = {
        "Name" = "terraformec2"
    }
    tenancy                      = "default"
    volume_tags                  = {}
    vpc_security_group_ids       = [
        "sg-0604857e6da455033",
    ]

    credit_specification {
        cpu_credits = "standard"
    }

    metadata_options {
        http_endpoint               = "enabled"
        http_put_response_hop_limit = 1
        http_tokens                 = "optional"
    }

    root_block_device {
        delete_on_termination = true
        device_name           = "/dev/sda1"
        encrypted             = false
        iops                  = 100
        volume_id             = "vol-048212ad297402dcb"
        volume_size           = 8
        volume_type           = "gp2"
    }

    timeouts {}
}

copy this resource data and paste in your main myresource.tf file. while pasting above code in myresource.tf file comment or remove the arn, id, instance_state, primary_network_interface_id, private_dns , public_dns , public_ip, device_name, volume_id.

That's it we have successfully imported ec2 instance using terraform import module.

 

Leave a Reply

Your email address will not be published. Required fields are marked *