Skip to content

Instantly share code, notes, and snippets.

@miry
Last active June 21, 2019 14:00
Show Gist options
  • Save miry/bf52ed5507b758a6d27762edea303992 to your computer and use it in GitHub Desktop.
Save miry/bf52ed5507b758a6d27762edea303992 to your computer and use it in GitHub Desktop.
Change ubuntu hostname with Terraform. `terraform apply -target=null_resource.set-hostname`
variable "server_ip" {
default = "10.0.0.2"
}
variable "server_hostname" {
default = "node01"
}
# Ubuntu reference for hostnamectl: http://manpages.ubuntu.com/manpages/trusty/man1/hostnamectl.1.html
resource "null_resource" "set-hostname" {
connection {
type = "ssh"
user = "ubuntu"
host = "${var.server_ip}"
}
provisioner "remote-exec" {
inline = [
"sudo hostnamectl set-hostname ${var.server_hostname}",
"echo '127.0.0.1 ${var.server_hostname}' | sudo tee -a /etc/hosts",
"sudo reboot"
]
}
}
@atrepca
Copy link

atrepca commented May 30, 2018

Another more elegant option: cloud-init passed on as user_data.

@paambaati
Copy link

@miry Does this need a reboot?

@nerdybreed
Copy link

nerdybreed commented Aug 13, 2018

thanks @miry. Your solution worked well except I had to change the order.
@paambaati a restart is not required. hostnamectl also sets local hostname. So it will reflect untill reboot. On reboot it will make it permanent.

  provisioner "remote-exec" {
    inline = [
      "echo '127.0.0.1 ${var.server_hostname}' | sudo tee -a /etc/hosts",
      "sudo hostnamectl set-hostname ${var.server_hostname}",
    ]
  }

@kimuthuselvan
Copy link

I followed the same but it is not working

Code:

resource "null_resource" "setup-httpd" {

connection {

type = "ssh"

	host = "${file("../ec2-instance/host_ip.txt")}"

	user = "ec2-user"

	private_key = "${file("../ec2-instance/aws_ssh_key")}"

	timeout = "30s"

}

provisioner "remote-exec" {

	inline = [

	"sudo yum install -y httpd mod_ssl"

	]

}

}

Copy link

ghost commented Apr 1, 2019

How to change hostname if security group limit IPs that can connect to instance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment