Skip to main content

SSH Key Authentication Setup

1. Generate SSH Key

# Generate ED25519 key (recommended)
ssh-keygen -t ed25519 -C "your-email@example.com"

# Press Enter for default location (~/.ssh/id_ed25519)
# Enter passphrase (optional)

2. Get Your Public Key

# Display public key
cat ~/.ssh/id_ed25519.pub

# Copy the ENTIRE line (from ssh-ed25519 to the end)

3. Add to Terraform Cloud/Enterprise

  1. Go to workspace → Variables
  2. Click Add variable
  3. Configure:
    • Key: authorized_keys
    • Value: ["ssh-ed25519 AAAAC3NzaC1... your-email@example.com"]
    • Category: Terraform variable
    • HCL: ✅ MUST CHECK THIS BOX (critical!)
    • Sensitive: ✅

IMPORTANT: Without the HCL checkbox, you'll get errors like "list of string required, but have string"

4. Update VM Configuration

In terraform.tfvars:

stackscript_data = {
permit_root_login = "yes" # REQUIRED to allow root login with SSH keys
password_authentication = "no" # Optional: disable password, use keys only
enable_forwarding = "yes"
enable_fail2ban = "yes"
custom_ports = "22,80,443,8080"
}

Note: permit_root_login = "yes" is required to connect as root, even with SSH keys. If set to "no", root cannot login at all (neither with keys nor password).

5. Connect to VM

Terminal

# Connect with SSH key
ssh root@YOUR_VM_IP

# Or specify key explicitly
ssh -i ~/.ssh/id_ed25519 root@YOUR_VM_IP

VSCode

  1. Install Remote - SSH extension
  2. Press F1Remote-SSH: Open SSH Configuration File
  3. Add to ~/.ssh/config:
   Host alpine-web
HostName YOUR_VM_IP
User root
IdentityFile ~/.ssh/id_ed25519
  1. Press F1Remote-SSH: Connect to Host → Select alpine-web

Multiple Users

Add multiple keys in TFE variable:

[
"ssh-ed25519 AAAAC3Nza... user1@laptop",
"ssh-ed25519 AAAAC3Nza... user2@desktop"
]

Troubleshooting

Invalid HCL Error

  • Make sure HCL checkbox is checked ✅
  • Value must be on ONE line (no line breaks)
  • Format: ["ssh-ed25519 AAAA... user@host"]

Connection Refused

# Test SSH connection
ssh -v root@YOUR_VM_IP

# Check key permissions (should be 600)
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

Permission Denied

  • Verify permit_root_login = "yes" in stackscript_data
  • Check authorized_keys variable is set in TFE with HCL checkbox

Security Best Practice

After first login, create a non-root user:

adduser yourname
echo "yourname ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/yourname
mkdir -p /home/yourname/.ssh
cp /root/.ssh/authorized_keys /home/yourname/.ssh/
chown -R yourname:yourname /home/yourname/.ssh
chmod 700 /home/yourname/.ssh
chmod 600 /home/yourname/.ssh/authorized_keys

Then disable root login: permit_root_login = "no"