Creating Host With Corresponding DNS entries
Technical Background
Solution
Prerequisits
Create the same files and folder structure as done before in exercise 19 Creating DNS Records.
Configuring Known Host Generator
- Add DNS Zone and Server Name Variable to
/Module/SshKnownHosts/variables.tf
:
variable "dnsZone" {
type = string
description = "DNS Zone of the server"
}
variable "serverName" {
type = string
description = "name of the server"
}
- Update the Known Host Wrapper ressource in
/Module/SshKnownHosts/main.tf
:
resource "local_file" "known_hosts" {
content = "${var.serverName}.${var.dnsZone} ${var.public_key}"
filename = "gen/known_hosts"
file_permission = "644"
}
- Add variables in
/KnownHostsByModule/main.tf
to üass the DNS Zone and Server Name to Module from parent:
module "createSshKnownHosts" {
source = "../Module/SshKnownHosts"
loginName = hcloud_ssh_key.loginUser.name
ip4Address = hcloud_server.web.ipv4_address
public_key = local_file.server_public_key.content
dnsZone = var.dns_zone
serverName = var.server_name
}
Use DNS Name instead of IP in ssh.sh
- Create Variable that replaces old
ip
variable and combines and stores DNS Name and DNS Zone insidelocal_file
ressource forssh.sh
:
resource "local_file" "ssh_script" {
content = templatefile("${path.module}/tpl/ssh.sh", {
dns = "${var.serverName}.${var.dnsZone}"
loginName = "${var.loginName}"
})
filename = "bin/ssh"
file_permission = "700"
depends_on = [local_file.known_hosts]
}
- Replace
ip
withdns
inside thessh.sh
template:
#!/usr/bin/env bash
GEN_DIR=$(dirname "$0")/../gen
ssh \
-o UserKnownHostsFile="$GEN_DIR/known_hosts" \
-o IdentitiesOnly=yes \
-i ~/.ssh/id_ed25519 \
${loginName}@${dns}
Deploy and Verify
Initialize and apply Terraform inside /KnownHostsByModule
:
terraform init
terraform apply
Success
There should be new /KnownHostsByModule/bin/ssh
and /KnownHostsByModule/gen/known_host
They should look like this:
gen/known_hosts:
workhorse.gxy.sdi.hdm-stuttgart.cloud ssh-ed25519 AAAAC3N...at8e8JL3rr
bin/ssh:
```
!/usr/bin/env bash
GEN_DIR=$(dirname "$0")/../gen
ssh -o UserKnownHostsFile="$GEN_DIR/known_hosts" devops@workhorse.gxy.sdi.hdm-stuttgart.cloud "$@"
end
```