Terraform: String & (manipolazione di) List

Intro

Oggi -tramite questo tutorial- voglio raccontarvi una situazione in cui mi sono imbattuto la scorsa settimana.

Stavo lavorando sulla parte IaC di un nuovo microservizio. Ad un certo punto (per motivi che salto) dovevo ottenere il nome del plan partendo dal App Service Plan Id (ricevuto in ingresso dalla pipeline)

Per chi non è pratico del mondo Azure, la stringa relativa al valore del App Service Plan Id ha la seguente struttura:

1
/subscriptions/subscription-id/resourceGroups/resource-group-id/providers/Microsoft.Web/serverFarms/app-plan-name

Il mio obiettivo era molto semplice: ottenere il valore “app-plan-name” presente in fondo. Come posso fare?

▶ Attenzione: il codice mostrato ha lo scopo di mostrare come funziona terraform, ma non corrisponde allo script “copia ed incolla” per essere eseguito a tempo zero.

Split della stringa

Il primo passaggio necessario per passare da una string ad una list consiste nel fare lo spit per un carattere separatore.

Nel seguente esempio vi mostrerò come effettuare questa operazione:

1
2
3
4
5
locals {
  azure_resource_id = "/subscriptions/subscription-id/resourceGroups/resource-group-id/providers/Microsoft.Web/serverFarms/app-plan-name"

  azure_resource_items = split("/", local.azure_resource_id)
}

Da questo momento utilizzeremo azure_resporce_items in quanto contiente tutto quello che occorre per potere procedere.

Come faccio a saperlo?

Struttando gli output abbiamo modo di vedere quello che vogliamo.

1
2
3
output "items_value" {
  value = local.azure_resource_items
}

In questo caso il risultato mostrato corrisponde al seguente:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
items_value = tolist([
  "",
  "subscriptions",
  "subscription-id",
  "resourceGroups",
  "resource-group-id",
  "providers",
  "Microsoft.Web",
  "serverFarms",
  "app-plan-name",
])

Escludere le stringhe vuote

Come avrete notato il primo valore di items_value corrisponde ad una stringa vuota. Posso escluderla oppure sono obbligato a tenerla nella mia lista?

Ovviamente possiamo farlo ed ecco come manipolare l’output per ottenere il risultato desiderato:

1
2
3
output "items_filtered_not_empty" {
  value = [for element in local.azure_resource_items : element if element != ""]
}

In questo caso il risultato mostrato corrisponde al seguente:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
items_filtered_not_empty = [
  "subscriptions",
  "subscription-id",
  "resourceGroups",
  "resource-group-id",
  "providers",
  "Microsoft.Web",
  "serverFarms",
  "app-plan-name",
]

Index/ Value

Vorresti sapere se (in qualche modo) hai la possibilità di passare da list a map dove la chiave corrisponde all’indice della lista ed il valore al value?

Per tua fortuna puoi arrivare a questo risultato in un attimo ed in maniera veramente semplice.

1
2
3
output "items_index_value" {
  value = { for index, element in local.azure_resource_items : index => element }
}

e dopo averlo eseguito ecco a voi il risultato desiderato

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
items_index_value = {
  "0" = ""
  "1" = "subscriptions"
  "2" = "subscription-id"
  "3" = "resourceGroups"
  "4" = "resource-group-id"
  "5" = "providers"
  "6" = "Microsoft.Web"
  "7" = "serverFarms"
  "8" = "app-plan-name"
}

Questo trucchetto risulta veramente utile se sei pigro e non hai voglia di contare a mano per cercare il valore che desideri.

Terraform CookBook

HashiCorp Configuration Language (HCL) has changed how we define and provision data center infrastructure with the launch of Terraform - a top-tier product for building Infrastructure as Code (IaC). Terraform Cookbook shows you how to leverage Terraform to manage complex cloud infrastructure with ease.

This new edition has been updated to include real-world examples for provisioning Cloud infrastructure(mainly for Azure, but also a dedicated chapter for AWS and GCP) with Terraform. You’ll delve into manual and automated testing with Terraform configurations, creating and managing a balanced, efficient, reusable infrastructure with Terraform modules. You’ll learn how to automate the deployment of Terraform configuration with continuous integration and continuous delivery (CI/CD). Besides, several new chapters have been added that describe the use of Terraform for Docker and Kubernetes, and explain how to test Terraform configurations using different tools to check code and security compliance. A complete chapter is dedicated to mastering Terraform Cloud and the latest chapter covers troubleshooting common Terraform issues and provides solutions for frequently encountered errors.

By the end of this book, you’ll have developed the skills needed to get the most value out of Terraform and to effectively manage your infrastructure.

Terraform Cookbook - Second Edition: Provision, run, and scale cloud architecture with real-world examples using Terraform