šŸ¶
Terraform

Add SSH Key to GCP Instance with Terraform

By Filip on 10/05/2024

Learn how to securely access your Google Cloud Platform instances by seamlessly adding SSH keys using Terraform with this step-by-step guide.

Add SSH Key to GCP Instance with Terraform

Table of Contents

Introduction

To add an SSH key to a Google Cloud Platform (GCP) instance using Terraform, follow these steps: Generate an SSH key pair if you don't have one already. Retrieve the public key from the generated file. In your Terraform code, locate the 'google_compute_instance' resource defining your GCP instance. Add a 'metadata' block within the resource if it doesn't exist. Inside 'metadata', add an entry with the key 'ssh-keys' and the value 'username:ssh-rsa <your_public_key>', replacing placeholders with your username and public key. Deploy your Terraform code using 'terraform apply'. You should now be able to SSH into your GCP instance using the corresponding private key.

Step-by-Step Guide

To add an SSH key to a Google Cloud Platform (GCP) instance using Terraform, you can follow these steps:

  1. Generate an SSH key pair: If you don't already have one, generate an SSH key pair on your local machine. You can use a command like ssh-keygen -t rsa to do this.

  2. Retrieve the public key: Open the public key file (usually ~/.ssh/id_rsa.pub or similar) and copy its contents.

  3. Use the google_compute_instance resource: In your Terraform code, locate the google_compute_instance resource that defines your GCP instance.

  4. Add the metadata block: Within the google_compute_instance resource, add a metadata block if it doesn't already exist.

  5. Specify the SSH key in metadata: Inside the metadata block, add an entry with the key ssh-keys and the value in the format username:ssh-rsa <your_public_key>. Replace <your_public_key> with the actual contents of your public key.

    resource "google_compute_instance" "default" {
      # ... other instance configurations ...
    
      metadata {
        ssh-keys = "your_username:ssh-rsa AAAAB3NzaC1yc2E... your_public_key"
      }
    }

    Replace "your_username" with your desired username on the instance.

  6. Deploy your Terraform code: Run terraform apply to deploy your changes to GCP. Terraform will provision the instance and embed your SSH key into the instance metadata.

Now, you should be able to SSH into your GCP instance using the corresponding private key.

Code Example

This Terraform code defines infrastructure on Google Cloud Platform. It sets up a Google Compute Instance using a Debian 9 image. The instance is configured with a network interface and has a user's SSH public key embedded in its metadata, allowing SSH access to the instance using the corresponding private key. Variables are used for project ID and zone, and a random project ID is generated for demonstration. Before running, replace placeholders with actual values and ensure proper authentication is set up.

# Configure the Google Cloud provider
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
      version = "~> 4.0"
    }
  }
}

# Configure variables for project ID and zone (replace with your values)
variable "project_id" {
  type = string
}

variable "zone" {
  type = string
}

# Generate a random project ID for demonstration purposes
resource "random_id" "project_id" {
  byte_length = 8
}

# Define the Google Compute Instance resource
resource "google_compute_instance" "default" {
  name         = "ssh-key-instance"
  machine_type = "n1-standard-1"
  zone         = var.zone
  project      = var.project_id

  # Use a pre-defined Debian image
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  # Define network interface
  network_interface {
    network = "default"
  }

  # Add your SSH public key to the instance metadata
  metadata = {
    ssh-keys = "your_username:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC123456789your_public_key_goes_here user@machine"
  }
}

Explanation:

  1. Provider Configuration: The code starts by configuring the Google Cloud provider, specifying the source and version.
  2. Variables: It defines variables for project_id and zone, allowing you to customize these values.
  3. Random ID: For demonstration purposes, it generates a random project ID using random_id. In a real-world scenario, you would use your actual project ID.
  4. Compute Instance: The google_compute_instance resource defines the GCP instance:
    • name, machine_type, zone, and project specify basic instance configurations.
    • boot_disk configures the boot disk using a Debian 9 image.
    • network_interface attaches the instance to the default network.
  5. Metadata with SSH Key: The metadata block is crucial:
    • It includes an entry with the key ssh-keys.
    • The value is in the format username:ssh-rsa <your_public_key>, where:
      • Replace "your_username" with your desired username.
      • Replace "AAAAB3NzaC1yc2EAAAADAQABAAABAQC123456789your_public_key_goes_here user@machine" with your actual public key.

Before running:

  • Replace placeholders: Ensure you replace the placeholders for project_id, zone, your_username, and your actual SSH public key.
  • Authentication: Make sure you have properly set up authentication for Terraform to interact with your GCP account (e.g., using Google Cloud SDK).

To deploy:

  1. Save the code as a .tf file (e.g., main.tf).
  2. Run terraform init to initialize the working directory.
  3. Run terraform apply to create the instance with your SSH key embedded.

After successful deployment, you should be able to SSH into your instance using the corresponding private key.

Additional Notes

Security:

  • Never embed your private SSH key directly in code or configuration files.
  • Use secure methods to manage sensitive information, such as environment variables, Terraform Cloud variables, or dedicated secrets management tools like HashiCorp Vault.
  • Consider using OS Login (for supported operating systems) as a more secure alternative to managing SSH keys directly.

Best Practices:

  • Use a dedicated SSH key pair for each GCP project or environment. This improves security isolation.
  • Store your SSH keys securely on your local machine. Use a strong passphrase to protect your private key.
  • Regularly rotate your SSH keys. This limits the impact of a potential key compromise.
  • Consider using a bastion host for accessing instances in private networks. This provides an extra layer of security.

Troubleshooting:

  • Verify that the SSH key you're using is correct. Double-check for typos in the public key and ensure you're using the corresponding private key for authentication.
  • Check firewall rules. Ensure that port 22 (SSH) is open in your GCP firewall rules for incoming traffic to your instance.
  • Review instance logs in the GCP console for any error messages related to SSH or authentication.

Alternatives:

  • Google Cloud Console: You can also add SSH keys directly through the Google Cloud Console interface.
  • gcloud command-line tool: The gcloud CLI provides commands for managing SSH keys in GCP.

Additional Considerations:

  • Instance templates: If you're using instance templates, you can embed the SSH key in the template's metadata to apply it to all instances created from that template.
  • Automated deployments: For automated deployments, consider using a configuration management tool like Ansible, Chef, or Puppet to manage SSH keys on your instances.

Summary

This guide outlines how to add an SSH key to a Google Cloud Platform instance during provisioning with Terraform.

Step Description
1. Generate SSH Key Pair Use ssh-keygen -t rsa on your local machine to create a public-private key pair if you don't have one already.
2. Retrieve Public Key Copy the contents of your public key file (e.g., ~/.ssh/id_rsa.pub).
3. Locate Instance Resource In your Terraform code, find the google_compute_instance resource defining your GCP instance.
4. Add Metadata Block Ensure a metadata block exists within the google_compute_instance resource.
5. Specify SSH Key Inside the metadata block, add an entry: ssh-keys = "your_username:ssh-rsa <your_public_key>". Replace placeholders with your username and the copied public key.
6. Deploy with Terraform Run terraform apply to provision the instance and embed your SSH key in its metadata.

After deployment, you can SSH into your GCP instance using the corresponding private key.

Conclusion

By following these steps, you can efficiently manage SSH access to your GCP instances during the provisioning process with Terraform. Remember to prioritize security by protecting your SSH keys, using strong passphrases, and considering alternatives like OS Login or bastion hosts for enhanced security measures. For troubleshooting, verify your SSH keys, check firewall rules, and review instance logs. Explore additional options like instance templates and configuration management tools for streamlined and automated SSH key management in your GCP environment.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait