Using Terraform Maps

Figure 1088. Server ip's by server name Slide presentation
# variables.tf
variable "ipByName" {
  type      = map(string)
  description = "IP's by server names"
}
# config.auto.tfvars
ipByName = { # key/value pairs
  mail = "192.178.1.3"
  database = "192.168.85.9"
}
#main.tf

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "2.7.0"
    }
  }
}
resource "local_file" "serverConfigs" {
  for_each = var.ipByName
  filename = "Generate/${each.key}.cfg"
  content  = "ipv4=${each.value}"
  file_permission = 0744
}

Figure 1089. Generated files Slide presentation
> terraform apply
...
local_file.serverConfigs["mail"]: Creation complete ...
local_file.serverConfigs["database"]: Creation complete ...

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

> ls Generate
database.cfg  mail.cfg

cat Generate/database.cfg 
ipv4=192.168.85.9

exercise No. 17

Multiple ssh keys access

Q:

Extend Using configuration variables by allowing multiple ssh public keys to access your server. Define a variable authorizedUsers of type map(string):

# config.auto.tfvars

authorizedUsers = {
  goik    = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKY24AeEibQGSMPtstaN4REByLCM3kzjM//apEZ9WyUB goik@hdm-stuttgart.de"
  xmlmind = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINFH4WsoUzIuOQwGPkLJNNcz9ngWJtWPcKXxW6LAfl1f xmlmind"
}

On execution the corresponding set of public keys shall be granted access:

> terraform apply

Apply complete! Resources: 4 added, 0 changed, 0 destroyed.                                                                                                                                                                                                          

Outputs:                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                     
servers = "(www|46.62.254.219)"


> ssh root@46.62.254.219
...

root@www:~# cat .ssh/authorized_keys 
ssh-ed25519 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKY24AeEibQGSMPtstaN4REByLCM3kzjM//apEZ9WyUB goik@hdm-stuttgart.de
ssh-ed25519 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINFH4WsoUzIuOQwGPkLJNNcz9ngWJtWPcKXxW6LAfl1f xmlmind