From 83be896f0650b3bc2518351dad2faa0cac3541e5 Mon Sep 17 00:00:00 2001 From: Florian Reinhold Date: Mon, 11 Apr 2022 23:16:21 +0200 Subject: [PATCH] feat: auto-gen ssh key when non provited --- main.tf | 4 ++++ outputs.tf | 10 ++++++++++ resources_hetzner.tf | 10 ++++++++-- variables.tf | 2 ++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/main.tf b/main.tf index ceb9e82..aa6e6bf 100644 --- a/main.tf +++ b/main.tf @@ -8,5 +8,9 @@ terraform { source = "rancher/rke" version = "1.3.0" } + tls = { + source = "hashicorp/tls" + version = "3.3.0" + } } } diff --git a/outputs.tf b/outputs.tf index a3f5d7c..d5d5fc0 100644 --- a/outputs.tf +++ b/outputs.tf @@ -31,3 +31,13 @@ output "lb_address" { description = "HCloud loadbalancer address" value = hcloud_load_balancer.rke_lb.ipv4 } + +output "hcloud_ssh_key_public" { + description = "registered ssh public key on your Hetzner Cloud machines." + value = var.hcloud_ssh_key_public != "" && var.hcloud_ssh_key_private != "" ? var.hcloud_ssh_key_public : tls_private_key.ssh_key_gen[0].public_key_openssh +} + +output "hcloud_ssh_key_private" { + description = "registered ssh private key on your Hetzner Cloud machines." + value = var.hcloud_ssh_key_public != "" && var.hcloud_ssh_key_private != "" ? var.hcloud_ssh_key_private : tls_private_key.ssh_key_gen[0].private_key_openssh +} diff --git a/resources_hetzner.tf b/resources_hetzner.tf index ea50f77..8c5e2cc 100644 --- a/resources_hetzner.tf +++ b/resources_hetzner.tf @@ -15,9 +15,15 @@ resource "hcloud_network" "kubernetes_internal_network" { } } +resource "tls_private_key" "ssh_key_gen" { + count = var.hcloud_ssh_key_public != "" && var.hcloud_ssh_key_private != "" ? 1 : 0 + algorithm = "RSA" + rsa_bits = 4096 +} + resource "hcloud_ssh_key" "rke_ssh_key" { name = "${var.instance_prefix}-rke-management-key" - public_key = var.hcloud_ssh_key_public + public_key = var.hcloud_ssh_key_public != "" && var.hcloud_ssh_key_private != "" ? var.hcloud_ssh_key_public : tls_private_key.ssh_key_gen[0].public_key_openssh labels = { automated = true } @@ -38,7 +44,7 @@ resource "hcloud_server" "rke_nodes" { connection { type = "ssh" user = "root" - private_key = var.hcloud_ssh_key_private + private_key = var.hcloud_ssh_key_public != "" && var.hcloud_ssh_key_private != "" ? var.hcloud_ssh_key_private : tls_private_key.ssh_key_gen[0].private_key_openssh host = self.ipv4_address } } diff --git a/variables.tf b/variables.tf index 2e21c32..39f775b 100644 --- a/variables.tf +++ b/variables.tf @@ -6,11 +6,13 @@ variable "hcloud_secret" { variable "hcloud_ssh_key_public" { type = string description = "ssh public key you want to use register on your Hetzner Cloud machines." + default = "" } variable "hcloud_ssh_key_private" { type = string description = "ssh private key you want to use register on your Hetzner Cloud machines." + default = "" } variable "instance_prefix" {