When provisioning infrastructure with Terraform, there are some resources that require passwords in their properties, such as VMs and databases.
To ensure better security by not writing passwords in clear text, you can use a Terraform provider, which allows you to generate passwords.
In this recipe, we will discuss how to generate a password with Terraform and assign it to a resource.
Getting ready
In this recipe, we need to provision a VM in Azure that will be provisioned with an administrator password generated dynamically by Terraform.
To do this, we will base ourselves on an already existing Terraform configuration that provisions a VM in Azure.
The source code for this recipe is available at https://github.com/PacktPublishing/Terraform-Cookbook/tree/master/CHAP02/password.
How to do it…
Perform the following steps:
- In the Terraform configuration file for the VM, add the following code:
resource "random_password" "password" {
length = 16
special = true
override_special = "_%@"
}
- Then, in the code of the resource itself, modify the password property with the following code:
resource "azurerm_virtual_machine" "myterraformvm" {
name = "myVM"
location = "westeurope"
resource_group_name = azurerm_resource_group.myterraformgroup.name
network_interface_ids = [azurerm_network_interface.myterraformnic.id]
vm_size = "Standard_DS1_v2"
....
os_profile {
computer_name = "vmdemo"
admin_username = "admin"
admin_password = random_password.password.result
}
....
}
How it works…
In step 1, we added the Terraform random_password resource from the random provider, which allows us to generate strings according to the properties provided. These will be sensitive, meaning that they're protected by Terraform.
Then, in step 2, we used its result (with the result property) in the password property of the VM.
The result of executing the terraform plan command on this code can be seen in the following screenshot:
As we can see, the result is sensitive value.
On the other hand, it will be present in clear text in the Terraform state file.
See also
- To find out more about the random_password resource, read the following documentation: https://www.terraform.io/docs/providers/random/r/password.html.
- Documentation regarding sensitive data in Terraform state files is available at https://www.terraform.io/docs/state/sensitive-data.html.