如何在不破坏它们的情况下使用 terraform 重启 EC2 实例?

How to restart EC2 instance using terraform without destroying them?

我想知道我们如何停止并重新启动使用 terraform 创建的 AWS ec2 实例。有什么办法吗?

如您所问,例如,评论有限制,因此使用 local-exec 作为答案发布。

我假设您已经使用 aws-cli 配置了 aws configure | aws configure --profile test

这是重启实例、更改 VPC SG ID、子网和密钥名称等的完整示例

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()}"
  }


}

现在运行terraform apply

一旦创建,您稍后想重新启动或停止,只需调用

terraform apply -target null_resource.reboo_instance

查看日志

我找到了更简单的方法。

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