How to restart EC2 instance using terraform without destroying them?

牧云@^-^@ 提交于 2020-08-07 07:45:12

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/57158310/how-to-restart-ec2-instance-using-terraform-without-destroying-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!