DEV Community

Cover image for 1.Create Key Pair Using Terraform - Level 1
Thu Kha Kyawe
Thu Kha Kyawe

Posted on

1.Create Key Pair Using Terraform - Level 1

Question

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.

Requirements:

  • Name of the key pair should be datacenter_kp
  • Key pair type must be rsa
  • The private key file should be saved under /home/bob/datacenter_kp.pem
  • The Terraform working directory is /home/bob/terraform
  • Create the main.tf file (do not create a different .tf file)

👉 Your task: Create a key pair using Terraform with the specified requirements for AWS infrastructure migration preparation.

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

Solutions

Step 1. Create main.tf

Create main.tf with the following content:

# Configure the AWS Provider
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# Configure AWS provider 
provider "aws" {
  region = "us-east-1"  
}

# Create the key pair
resource "tls_private_key" "datacenter_kp" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

# Create AWS key pair
resource "aws_key_pair" "datacenter_kp" {
  key_name   = "datacenter-kp"
  public_key = tls_private_key.datacenter_kp.public_key_openssh
}

# Save the private key to file
resource "local_file" "private_key" {
  content  = tls_private_key.datacenter_kp.private_key_pem
  filename = "/home/bob/datacenter-kp.pem"
  file_permission = "0400"
}

# Output the key pair name (optional)
output "key_pair_name" {
  value = aws_key_pair.datacenter_kp.key_name
}
Enter fullscreen mode Exit fullscreen mode

Step 2. Initialize Terraform Configuration

Now, let's initialize and apply the Terraform configuration:

Initialize Terraform

terraform init
Enter fullscreen mode Exit fullscreen mode

Step 3. Apply Terraform Configuration

Apply the configuration

terraform apply
Enter fullscreen mode Exit fullscreen mode


Related Resources


Credits

  • All labs are from: KodeKloud
  • Thanks for providing them.

Top comments (0)