Subbu
Subbu

Reputation: 663

How to restart EC2 instance using terraform without destroying them?

I am wondering how can we stop and restart the AWS ec2 instance created using terraform. is there any way to do that?

Upvotes: 12

Views: 26381

Answers (3)

Tomasz Chmielewski
Tomasz Chmielewski

Reputation: 51

Using remote-exec:

  provisioner "remote-exec" {
    inline = [
      "sudo /usr/sbin/shutdown -r 1"
    ]
  }

-r 1 is to delay the reboot and prevent remote-exec command exiting with non-zero code.

Upvotes: 2

Yevgen Taradayko
Yevgen Taradayko

Reputation: 155

I have found simpler way to do it.

provisioner "local-exec" {
command = "ssh -tt -o StrictHostKeyChecking=no 
                   someuser@${aws_eip.ec2_public_ip.public_ip} sudo 'shutdown -r'"
}

Upvotes: 0

Adiii
Adiii

Reputation: 60046

As you asked, for example, there is a limit on the comment, so posting as the answer using local-exec.

I assume that you already configure aws configure | aws configure --profile test using aws-cli.

Here is the complete example to reboot an instance, change VPC SG ID, subnet and key name etc

provider "aws" {
  region              = "us-west-2"
  profile             = "test"
}

resource "aws_instance" "ec2" {
  ami                         = "ami-0f2176987ee50226e"
  instance_type               = "t2.micro"
  associate_public_ip_address = false
  subnet_id                   = "subnet-45454566645"
  vpc_security_group_ids      = ["sg-45454545454"]
  key_name                    = "mytest-ec2key"
  tags = {
    Name = "Test EC2 Instance"
  }
}
resource "null_resource" "reboo_instance" {

  provisioner "local-exec" {
    on_failure  = "fail"
    interpreter = ["/bin/bash", "-c"]
    command     = <<EOT
        echo -e "\x1B[31m Warning! Restarting instance having id ${aws_instance.ec2.id}.................. \x1B[0m"
        # aws ec2 reboot-instances --instance-ids ${aws_instance.ec2.id} --profile test
        # To stop instance
        aws ec2 stop-instances --instance-ids ${aws_instance.ec2.id} --profile test
        echo "***************************************Rebooted****************************************************"
     EOT
  }
#   this setting will trigger script every time,change it something needed
  triggers = {
    always_run = "${timestamp()}"
  }


}

Now Run terraform apply

Once created and you want later to reboot or stop just call

terraform apply -target null_resource.reboo_instance

See the logs

enter image description here

Upvotes: 14

Related Questions