Trying to set Windows Hostname on an instance launched by Terraform

Viewed 208

I am trying to set a hostname on a Windows instance that I have launched from AWS account by Terraform. I can set the hostname with the help of a host.ps1 script. But everytime I launch a new instance i have to manually change the hostname hard coded inside the host.ps1 script file. So i wanted to do this with the help of a variable that i can specify during runtime or with 'Terraform apply'. This is the code I am trying with but its not happening.

I would also like to do the same thing on a linux platform later and for that i know i might have to use an sh file to accomplish that, but i dont know the exact process.

Can anybody help me?

Here are my code:

main.tf:

    resource "aws_instance" "terra" {
  
   
    ami = "ami-*****"
    instance_type = "t3.xlarge"
    
    tags = {
      #Name = "terra-test-Pega8.7"
      Name = var.hostname
      Accesibility = "Public"
      
    }
    subnet_id = "subnet-0ba2da79c625a1513"
    security_groups = ["sg-0d433ad46d13b2a0c"]
    key_name = "windows-key"
    
    user_data = file("host.ps1 ${var.hostname}")  # (here i tried only the hostname first which 
                                                    worked but i wanted to put the hostname in a 
                                                    variable later , so i tried this)
  

}
  
  variable "hostname" {
     type = string
     description = "Sets a hostname of the created instance"
     #default = "terratest"
   } 


resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.terra.id
  allocation_id = aws_eip.elasticip.id
}

resource "aws_eip" "elasticip" {
  vpc = true
}

here is the host.ps1 file:

param([String]$hname)
Rename-Computer -NewName $hname -Force -Restart

Here is the code first which worked previously

Rename-Computer -NewName 'terratest' -Force -Restart

**Actually i am very new to this so dont know much about these codes, so if anybody can guide that will be very helpful. Thank you in advance.

1 Answers

You're trying to pass parameters in something that's loading up a file for your user_data which won't work. If you want to pass terraform variables into your user_data, you could try inlining your bootstrap script into the terraform file:

resource "aws_instance" "terra" {
  // Your stuff here

  user_data = <<EOF
<powershell>
  Rename-Computer -NewName ${var.hostname} -Force -Restart
</powershell>
EOF
}

A neater way would be to use a template_file:

data "template_file" "user_datapowershell" {
  template = <<EOF
<powershell>
Rename-Computer -NewName ${var.hostname} -Force -Restart
</powershell>
EOF
}

resource "aws_instance" "terra" {
  // Your stuff here

  user_data = data.template_file.user_datapowershell.rendered
}
Related