Home > Back-end >  Terraform template_file resource with for_each variables
Terraform template_file resource with for_each variables

Time:09-06

I'm trying to write a user data template file with a map containing user group access but cannot find any examples of this being done anywhere and not sure how to go about it. Is it possible?

Here is what I'm trying to achieve:

Example of terraform.tfvars:

group_membership = {
  backup_folder_access = [
    "fred",
    "alice"
  ],
  full_folder_access = [
    "greg"
  ]
}

Example of userdata.ps1.tpl:

foreach ($group in ${group_membership}){
  New-LocalGroup -Name $group.key
  foreach ($user in ${group}.value){
    Add-LocalGroupMember -Group $group -Member $user
}

Example of template_file resource:

data "template_file" "userdata" {
  template = file("${path.module}/src/userdata.ps1.tpl")
  vars = {
    group_membership = "${var.group_membership}"
}

This is clearly incorrect, anyone know how this should look?

CodePudding user response:

These days you should use templatefile, not template_file. Then it would be:

your template:

%{for group, value in group_membership ~}
  New-LocalGroup -Name ${group}
  %{for user in value ~}
    Add-LocalGroupMember -Group ${group} -Member ${user}
  %{ endfor ~}    
%{ endfor ~}

and templatefile:

locals {
  userdata = templatefile("${path.module}/src/userdata.ps1.tpl", {
                  group_membership = var.group_membership
             })  
}
  • Related