DEV Community

Cover image for 8.Create AMI Using Terraform
Thu Kha Kyawe
Thu Kha Kyawe

Posted on

8.Create AMI Using Terraform

Lab Information

The Nautilus DevOps team is strategizing the migration of a portion of their infrastructure to the AWS cloud. Recognizing the scale of this undertaking, they have opted to approach the migration in incremental steps rather than as a single massive transition. To achieve this, they have segmented large tasks into smaller, more manageable units. This granular approach enables the team to execute the migration in gradual phases, ensuring smoother implementation and minimizing disruption to ongoing operations. By breaking down the migration into smaller tasks, the Nautilus DevOps team can systematically progress through each stage, allowing for better control, risk mitigation, and optimization of resources throughout the migration process.

For this task, create an AMI from an existing EC2 instance named xfusion-ec2 using Terraform.

Name of the AMI should be xfusion-ec2-ami, make sure AMI is in available state.

The Terraform working directory is /home/bob/terraform. Update the main.tf file (do not create a separate .tf file) to create the AMI.

Note: Right-click under the EXPLORER section in VS Code and select Open in Integrated Terminal to launch the terminal.
Enter fullscreen mode Exit fullscreen mode

Lab Solutions

Create main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

# Provision EC2 instance
resource "aws_instance" "ec2" {
  ami           = "ami-0c101f26f147fa7fd"
  instance_type = "t2.micro"
  vpc_security_group_ids = [
    "sg-dd1d59eaf2fd7d31e"
  ]

  tags = {
    Name = "xfusion-ec2"
  }
}

# Create AMI from the EC2 instance
resource "aws_ami_from_instance" "xfusion-ec2-ami" {
  name               = "xfusion-ec2-ami"
  source_instance_id = aws_instance.ec2.id
}
Enter fullscreen mode Exit fullscreen mode

This configuration:

Uses a data source to find the existing EC2 instance named xfusion-ec2

Creates an AMI from that existing instance with the name xfusion-ec2-ami

Waits for the AMI to become available

Outputs the AMI details for verification

To deploy:

cd /home/bob/terraform
terraform init
terraform plan
terraform apply
Enter fullscreen mode Exit fullscreen mode

Then type yes to confirm. The AMI creation will take several minutes, and Terraform will wait for it to become available.


Resources & Next Steps
πŸ“¦ Full Code Repository: KodeKloud Learning Labs
πŸ“– More Deep Dives: Whispering Cloud Insights - Read other technical articles
πŸ’¬ Join Discussion: DEV Community - Share your thoughts and questions
πŸ’Ό Let's Connect: LinkedIn - I'd love to connect with you

Credits
β€’ All labs are from: KodeKloud
β€’ I sincerely appreciate your provision of these valuable resources.

Top comments (0)