title: How do I dynamincally rename EC2 windows hosts in an Autoscaling group using Terraform Userdata?
body: <p>I am passing the userdata through terraform which changes the windows EC2 hostname. This userdata configuration is part of an autoscaling group launch configuration. For each windows EC2 instance which spins up in this Autoscaling group, I need to assign a different hostname. Like adding a number at the end of specified hostname - Eg. hostnamedev (hostnamedev01, hostnamedev02, ...). Thank you</p>
  <p><em>init.ps1</em></p>
  <pre><code>#&lt;&lt;=======&lt;&lt;=======||Environment Variables from User Data||=========&gt;&gt;========&gt;&gt;
  $newHostname = &quot;${hostname}&quot;
  
  #&lt;&lt;===========================||Hostname Change||=============================&gt;&gt;
  function UpdateHostname {
    param (
      [Parameter (Mandatory = $true)]
      [string]$newHostname
    )
  
    If ($newHostname -ne $env:COMPUTERNAME) {
      
      Try {
        Rename-Computer -NewName $newHostname -Restart -ErrorAction Stop
      }  
      Catch {
        $ErrorMessage = $_.Exception.Message
        Write-Output &quot;Rename failed: $ErrorMessage&quot;
      }
    }
    else {
      Write-Output &quot;The Host Name is Updated already&quot;
    }
    Write-Output &quot;The Host Name is $env:COMPUTERNAME&quot;
  }
  
  UpdateHostname -newhostname $newHostname
  </code></pre>
  <p><em>userdata.tf</em></p>
  <pre><code>data &quot;template_file&quot; &quot;user_data&quot; {
    template = &quot;${file(&quot;${path.module}/init.ps1&quot;)}&quot;
    vars = {
      hostname     = &quot;hostnamedev&quot;
    }
  }
  </code></pre>
  <p><em>module.tf</em></p>
  <pre><code>module my_module {
    #...
    user_data                          = data.template_file.user_data.rendered
  }
  </code></pre>
  <p><em>ec2.tf</em></p>
  <pre><code>resource aws_launch_configuration launch_config {
    image_id                    = var.ami_id
    instance_type               = var.instance_type
    iam_instance_profile        = var.iam_instance_profile_name
    key_name                    = var.key_name
    user_data                   = var.user_data
  }
  
  resource aws_autoscaling_group asg {
    launch_configuration      = aws_launch_configuration.launch_config.name
    max_size                  = var.max_node
    min_size                  = var.min_node
    force_delete              = true
  
    lifecycle {
      create_before_destroy = true
    }
  }
  </code></pre>