如何使用 terraform 重新启动 EC2 实例而不破坏它们? [英] How to restart EC2 instance using terraform without destroying them?
问题描述
我想知道如何停止和重新启动使用 terraform 创建的 AWS ec2 实例.有没有办法做到这一点?
I am wondering how can we stop and restart the AWS ec2 instance created using terraform. is there any way to do that?
推荐答案
例如,如您所问,评论有限制,因此使用 local-exec
作为答案发布.
As you asked, for example, there is a limit on the comment, so posting as the answer using local-exec
.
我假设您已经配置了 aws configure |aws 配置 --profile test
使用 aws-cli.
I assume that you already configure aws configure | aws configure --profile test
using aws-cli.
这是重启实例、更改 VPC SG ID、子网和密钥名称等的完整示例
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()}"
}
}
现在运行 terraform apply
一旦创建,您想稍后重新启动或停止调用
Once created and you want later to reboot or stop just call
terraform apply -target null_resource.reboo_instance
查看日志
这篇关于如何使用 terraform 重新启动 EC2 实例而不破坏它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!