Execute bash script on Ubutnu using Terraform

Viewed 32

Is it possible to execute shell commands on Ubuntu OS using Terraform script?

I have to do some initial configuration before execution of Terraform scripts.

2 Answers

Depends upon where your Ubuntu OS is, if its local then you can do something like this

resource "aws_instance" "web" {
  # ...

  provisioner "local-exec" {
    command = "echo ${self.private_ip} >> private_ips.txt"
  }
}

If its a remote resource for example an aws ec2 instance:

resource "aws_instance" "web" {
  # ...

  # Establishes connection to be used by all
  # generic remote provisioners (i.e. file/remote-exec)
  connection {
    type     = "ssh"
    user     = "root"
    password = var.root_password
    host     = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "puppet apply",
      "consul join ${aws_instance.web.private_ip}",
    ]
  }
}

Also, if its an ec2-instance, one thing that is mostly used is defining a script using user_data which runs immediately after the resource is created with root privileges but only once and then will never run even if you reboot the instance. In terraform you can do something like this:

resource "aws_instance" "server" {
  ami                         = "ami-123456"
  instance_type               = "t3.medium"
  availability_zone           = "eu-central-1b"
  vpc_security_group_ids      = [aws_security_group.server.id]
  subnet_id                   = var.subnet1
  private_ip                  = var.private-ip
  key_name                    = var.key_name
  associate_public_ip_address = true
  tags = {
    Name = "db-server"
  }

  user_data = <<EOF
mkdir abc
apt update && apt install nano
EOF
}
Related