【问题标题】:How to restart EC2 instance using terraform without destroying them?如何使用 terraform 重新启动 EC2 实例而不破坏它们?
【发布时间】:2019-12-01 03:43:09
【问题描述】:

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

【问题讨论】:

  • Terraform 是building, changing, and versioning infrastructure安全高效的工具。所以关闭或重启你可以使用local-exec来实现。 Terraform 将摧毁...terraform destroy linkedin.com/pulse/…
  • 这是有道理的。你能举一个使用 local-exec 关闭或重启实例的例子吗?
  • 请看无法作为评论发布 Subbu

标签: terraform terraform-provider-aws


【解决方案1】:

例如,如您所问,评论有限制,因此使用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

查看日志

【讨论】:

【解决方案2】:

我找到了更简单的方法。

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

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2020-03-10
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2021-12-08
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多