我想知道如何停止和重新启动使用terraform创建的AWS ec2实例。有什么办法吗?
答案 0 :(得分: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
查看日志