Terraform modules


Figure 1034. Example: Creating bin/ssh and gen/known_hosts Slide presentation
main.tf Generated files
resource "tls_private_key" "host" {
  algorithm   = "ED25519"
}
resource "hcloud_ssh_key" "loginUser" {
  name       = "devops"
  public_key = file("~/.ssh/id_ed25519.pub")
}
resource "hcloud_server" "server" {
  name         = "www" ...
}
resource "local_file" "ssh_script" {
  content = templatefile("tpl/ssh.sh", {
    ip             = hcloud_server.helloServer.ipv4_address
    devopsUsername = hcloud_ssh_key.loginUser.name
  })
  filename        = "bin/ssh"
  depends_on      = [local_file.known_hosts]
}
  • Template file tpl/ssh.sh

  • gen/known_hosts

    94.130.229.221 ssh-ed25519 AAAAC3NzaC1lZDI1N...
    www.g03.sdi.hdm-stuttgart.cloud ssh-ed25519 ...
  • bin/ssh

    #!/usr/bin/env bash
    
    GEN_DIR=$(dirname "$0")/../gen
    
    ssh -o UserKnownHostsFile="$GEN_DIR/known_hosts" \
       devops@www.g03.sdi.hdm-stuttgart.cloud "$@"

Figure 1035. Local file generation by module Slide presentation
main.tf Using a module
resource "local_file" "known_hosts" {
  ...
}

resource "local_file" "ssh_script" {
  ...
}

resource "local_file" "scp_script" {
  ...
}
module "localfiles" {
  source    = "../modules/localfiles"

  ipv4       = hcloud_server.webServer.ipv4_address
  dnsZone    = var.dnsZone
  hostNames  = ["www", "cloud"]
  loginUser  = hcloud_ssh_key.loginUser.name
  hostKey    = tls_private_key.host.public_key_openssh
}

Figure 1036. Module implementation Slide presentation
variable "ipv4" {
  description = "The server's IPV4 address e.g. '141.62.1.5'"
  type        = string
}

variable "hostNames" {
  description = "Set of unique local host names e.g. [\"www\", \"cloud\"] "
  type        = list
}
...
resource "local_file" "known_hosts" {...

Figure 1037. Careful: local vs. parent context Slide presentation

Switching between parent and child module context by ${path.module}:

resource "local_file" "ssh_script" {
  content = templatefile("${path.module}/tpl/ssh.sh", {
    serverFqdn     = "${var.ostNames}.${var.dnsZone}"
    devopsUsername = var.loginUser
  })
  filename        = "bin/ssh"
  file_permission = "755"
  depends_on      = [local_file.known_hosts]
}

exercise No. 16

A module for local file generation

Q:

Complete the idea of Figure 1035, “Local file generation by module ” defining a module for generating bin/ssh and gen/known_hosts.