Skip to content

SSH Tunnel Automation

This guide provides various methods to automate the SSH tunnel for accessing your K3s cluster.

Basic SSH Tunnel

The basic SSH tunnel command:

ssh -N -L 6443:localhost:6443 ubuntu@YOUR_PUBLIC_IP

Automation Options

autossh provides automatic reconnection if the connection drops:

# Install autossh
sudo apt-get install autossh

# Create a persistent tunnel
autossh -M 0 -N -L 6443:localhost:6443 ubuntu@YOUR_PUBLIC_IP

2. Systemd Service

Create a systemd service for automatic tunnel management:

# Create service file
sudo nano /etc/systemd/system/k3s-tunnel.service

Add the following content:

[Unit]
Description=K3s SSH Tunnel
After=network.target

[Service]
User=YOUR_USERNAME
ExecStart=/usr/bin/autossh -M 0 -N -L 6443:localhost:6443 ubuntu@YOUR_PUBLIC_IP
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable k3s-tunnel
sudo systemctl start k3s-tunnel

3. Shell Script

Create a simple shell script for manual tunnel management:

# Create tunnel script
nano ~/k3s-tunnel.sh

Add the following content:

#!/bin/bash
ssh -N -L 6443:localhost:6443 ubuntu@YOUR_PUBLIC_IP

Make it executable:

chmod +x ~/k3s-tunnel.sh

4. SSH Config

Configure SSH for easier connection management:

# Add to ~/.ssh/config
nano ~/.ssh/config

Add the following configuration:

Host k3s-tunnel
    HostName YOUR_PUBLIC_IP
    User ubuntu
    LocalForward 6443 localhost:6443
    ServerAliveInterval 60
    ServerAliveCountMax 3

Then you can simply use:

ssh k3s-tunnel

Troubleshooting

Common Issues

  1. Connection Drops
  2. Check your network connection
  3. Verify the server is running
  4. Check SSH server logs: journalctl -u ssh

  5. Permission Denied

  6. Verify SSH key permissions: chmod 600 ~/.ssh/id_rsa
  7. Check SSH config permissions: chmod 600 ~/.ssh/config

  8. Port Already in Use

  9. Check if port 6443 is already in use: netstat -tuln | grep 6443
  10. Kill existing process: kill $(lsof -t -i:6443)

Monitoring

  1. Check Tunnel Status ```bash # For systemd service systemctl status k3s-tunnel

# For autossh ps aux | grep autossh ```

  1. View Logs ```bash # Systemd service logs journalctl -u k3s-tunnel -f

# SSH logs tail -f /var/log/auth.log ```

Security Considerations

  1. SSH Key Management
  2. Use strong SSH keys
  3. Regularly rotate keys
  4. Use key-based authentication only

  5. Network Security

  6. Restrict SSH access to specific IPs
  7. Use non-standard SSH port
  8. Enable fail2ban

  9. Monitoring

  10. Monitor failed login attempts
  11. Set up alerts for suspicious activity
  12. Regular security audits