Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Subbu Avatar asked Jul 23 '19 06:07

Subbu


People also ask

Can we start and stop EC2 instance using Terraform?

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. so shutdown or restart you can achieve this using local-exec.

How do you prevent force replacement in Terraform?

In general the best way to control this is using the lifecycle block to specify attributes that you do not want to force a new resource. As @Adrian mentions you need to show the full plan output for that resource to show why Terraform needs to replace the resource instead of modify it in place.


1 Answers

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

like image 164
Adiii Avatar answered Sep 21 '22 18:09

Adiii