8
votes

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

1
Terraform is a tool for building, changing, and versioning infrastructuresafely and efficiently. so shutdown or restart you can achieve this using local-exec. Terraform will destroy...terraform destroy linkedin.com/pulse/…Adiii
That makes sense. Can you give an example to shutdown or restart instances using local-exec?Subbu
Pls look was not able to post as a comment SubbuAdiii

1 Answers

7
votes

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