terraform,

random_password and multiple Terraform resource instances

Jun 21, 2022 · 1 min read · Post a comment

random_password is a Terraform resource used for generating as the name suggests, random passwords which could be utilized for sensitive secret’s initialization of other resources – users, databases, etc. Here I’m going to show you how to reuse random_password when deploying multiple instances of a single TF resource.

Prerequisites

  • Terraform

Solution(s)

Example code:

## variables.tf
variable "devcoops_users" {
  description = "A list of devcoops Azure AD users."
  default     = []
}

variable "domain_name" {
  description = "Domain name."
  type        = string
  default     = "devcoops.com"
}

## terraform.tfvars
devcoops_users = ["cade.mcphee", "owain.connolly"]

## main.tf
resource "random_password" "passwords" {
  count  = length(var.devcoops_users)
  length = 16
}

resource "azuread_user" "devcoops" {
  count = length(var.devcoops_users)

  user_principal_name = "${var.devcoops_users[count.index]}@${var.domain_name}"
  display_name        = var.devcoops_users[count.index]
  password            = random_password.passwords[count.index].result
}

Basically, generate password for each member of the devcoops_users list with 16 characters in length.

Conclusion

If you have any related unresolved issues, feel free to share them in the comment section below. On a side note, follow our official channel on Telegram.