这是 terraform 的非常多的用例,如果您能通过 terraform 来做会很好。
您可以按照下面的代码来启动任意数量的实例,您必须在更改count 值后再次申请。它不会影响任何当前正在运行的实例并匹配您的值。
resource "aws_instance" "web" {
ami = "${data.aws_ami.ubuntu.id}"
instance_type = "t2.micro"
count = 3
availability_zone = "${element(var.az, count.index)}"
tags {
Name = "${count.index}"
}
}
另外,如果您想在实例启动时执行某些命令。您可以使用用户数据脚本来执行此操作。
resource "aws_instance" "..." {
user_data = "${file("../../tmp/aws/userdata.sh")}"
...
}
为了可重复性,您可以使用 terraform 模块。例如:如果您想将代码用于多个基础设施,例如开发、登台、生产。对于模块,您不必一次又一次地编写相同的代码来启动 ec2 实例。您可以为不同的基础设施传递不同的变量。
例子:
module "dev" {
source = "./modules/dev"
count = 2
region = "us-east-1"
}
module "production" {
source = "./modules/production"
count = 5
region = "us-east-1"
}
参考:https://www.terraform.io/docs/modules/usage.html
如果您不必删除旧实例并减少正在运行的实例数量。这不是 terraform 会处理的问题。
您必须在创建自动扩展策略时提及该策略。
下面列出了许多终止政策。
Amazon EC2 Auto Scaling 支持以下自定义终止策略:
OldestInstance. Terminate the oldest instance in the group. This option is useful when you're upgrading the instances in the Auto Scaling group to a new EC2 instance type. You can gradually replace instances of the old type with instances of the new type.
NewestInstance. Terminate the newest instance in the group. This policy is useful when you're testing a new launch configuration but don't want to keep it in production.
OldestLaunchConfiguration. Terminate instances that have the oldest launch configuration. This policy is useful when you're updating a group and phasing out the instances from a previous configuration.
ClosestToNextInstanceHour. Terminate instances that are closest to the next billing hour. This policy helps you maximize the use of your instances and manage your Amazon EC2 usage costs.
Default. Terminate instances according to the default termination policy. This policy is useful when you have more than one scaling policy for the group.
您可以参考以下链接了解更多信息。
参考:
https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html