title: How to set hostname with cloud-init and Terraform?
body: <p>I am starting with Terraform. I am trying to make it set a friendly hostname, instead of the usual <code>ip-10.10.10.10</code> that AWS uses. However, I haven't found how to do it.</p>
  
  <p>I tried using provisioners, like this:</p>
  
  <pre><code>provisioner "local-exec" {
     command = "sudo hostnamectl set-hostname friendly.example.com"
  }
  </code></pre>
  
  <p>But that doesn't work, the hostname is not changed.</p>
  
  <p>So now, I'm trying this:</p>
  
  <pre><code>resource "aws_instance" "example" {
    ami           = "ami-XXXXXXXX"
    instance_type = "t2.micro"
    tags = {
      Name    = "friendly.example.com"
    }
    user_data = "${data.template_file.user_data.rendered}"
  }
  
  data "template_file" "user_data" {
    template = "${file("user-data.conf")}"
    vars {
      hostname = "${aws_instance.example.tags.Name}"
    }
  }
  </code></pre>
  
  <p>And in <code>user-data.conf</code> I have a line to use the variable, like so:</p>
  
  <pre><code>hostname = ${hostname}
  </code></pre>
  
  <p>But this gives me a cycle dependency:</p>
  
  <pre><code>$ terraform apply
  Error: Error asking for user input: 1 error(s) occurred:
  * Cycle: aws_instance.example, data.template_file.user_data
  </code></pre>
  
  <p>Plus, that would mean I have to create a different <code>user_data</code> resource for each instance, which seems a bit like a pain. Can you not reuse them? That should be the purpose of templates, right?</p>
  
  <p>I must be missing something, but I can't find the answer.
  Thanks.</p>