如何自动停止和启动 AWS EC2 实例
how to stop and start AWS EC2 instance automatically
我是使用 AWS 的初学者。
我只是想定期自动停止和启动几个 EC2 实例(不重启)。
有推荐的方法吗?
是的,您可以使用 AWS Lambda 做到这一点。您可以 select Cloudwatch 中的触发器,它 运行 在 UTC 上的 Cron 表达式上。
这里是相关的linkhttps://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
另一种选择是使用 awscli
,可从 pip
、apt-get
、yum
或 brew
获得,然后使用 运行使用您来自 IAM 的凭据连接 aws configure
并执行以下 bash 脚本,以停止标记有 Name: Appname
和 Value: Appname Prod
的 EC2。您可以使用 awscli
标记您的实例或从 AWS 控制台手动标记它。 aws ec2 stop-instances
将停止实例,jq
用于过滤 json 查询并使用来自 aws ec2 describe-instances
.
的标签获取正确的实例 ID
验证 aws configure
是否成功并且 returns json 输出 运行 aws ec2 describe-instances
和你的 运行ning 实例 ID 应该在那里在输出中。这是一个示例输出
{
"Reservations": [
{
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-xxx.ap-south-1.compute.amazonaws.com",
"State": {
"Code": xx,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "20xx-xx-xxTxx:16:xx.000Z",
"PublicIpAddress": "xx.127.24.xxx",
"PrivateIpAddress": "xxx.31.3.xxx",
"ProductCodes": [],
"VpcId": "vpc-aaxxxxx",
"StateTransitionReason": "",
"InstanceId": "i-xxxxxxxx",
"ImageId": "ami-xxxxxxx",
"PrivateDnsName": "ip-xxxx.ap-south-1.compute.internal",
"KeyName": "node",
"SecurityGroups": [
{
"GroupName": "xxxxxx",
"GroupId": "sg-xxxx"
}
],
"ClientToken": "",
"SubnetId": "subnet-xxxx",
"InstanceType": "t2.xxxxx",
"NetworkInterfaces": [
{
"Status": "in-use",
"MacAddress": "0x:xx:xx:xx:xx:xx",
"SourceDestCheck": true,
"VpcId": "vpc-xxxxxx",
"Description": "",
"NetworkInterfaceId": "eni-xxxx",
"PrivateIpAddresses": [
{
"PrivateDnsName": "ip-xx.ap-south-1.compute.internal",
"PrivateIpAddress": "xx.31.3.xxx",
"Primary": true,
"Association": {
"PublicIp": "xx.127.24.xxx",
"PublicDnsName": "ec2-xx.ap-south-1.compute.amazonaws.com",
"IpOwnerId": "xxxxx"
}
}
],
"PrivateDnsName": "ip-xxx-31-3-xxx.ap-south-1.compute.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "xxx",
"AttachTime": "20xx-xx-30Txx:16:xx.000Z"
},
"Groups": [
{
"GroupName": "xxxx",
"GroupId": "sg-xxxxx"
}
],
"Ipv6Addresses": [],
"OwnerId": "xxxx",
"PrivateIpAddress": "xx.xx.xx.xxx",
"SubnetId": "subnet-xx",
"Association": {
"PublicIp": "xx.xx.xx.xxx",
"PublicDnsName": "ec2-xx.ap-south-1.compute.amazonaws.com",
"IpOwnerId": "xxxx"
}
}
],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": "",
"AvailabilityZone": "xx"
},
"Hypervisor": "xxx",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xxx",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-xxx",
"AttachTime": "20xxx-xx-xxTxx:16:xx.000Z"
}
}
],
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/xxx",
"VirtualizationType": "xxx",
"Tags": [
{
"Value": "xxxx centxx",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
],
"ReservationId": "r-xxxx",
"Groups": [],
"OwnerId": "xxxxx"
}
]
}
下面的bash脚本是stop-ec2.sh
在/home/centos/cron-scripts/
(instance=$(aws ec2 describe-instances | jq '.Reservations[].Instances | select(.[].Tags[].Value | startswith("Appname Prod") ) | select(.[].Tags[].Key == "Appname") | {InstanceId: .[].InstanceId, PublicDnsName: .[].PublicDnsName, State: .[].State, LaunchTime: .[].LaunchTime, Tags: .[].Tags} | [.]' | jq -r .[].InstanceId) && aws ec2 stop-instances --instance-ids ${instance} )
运行 使用 sh /home/centos/cron-scripts/stop-ec2.sh
的文件并验证 EC2 实例是否已停止。调试 运行 aws ec2 describe-instances | jq '.Reservations[].Instances | select(.[].Tags[].Value | startswith("Appname Prod") ) | select(.[].Tags[].Key == "Appname") | {InstanceId: .[].InstanceId, PublicDnsName: .[].PublicDnsName, State: .[].State, LaunchTime: .[].LaunchTime, Tags: .[].Tags} | [.]' | jq -r .[].InstanceId
并查看它 returns 已标记的正确实例 ID。
然后在crontab -e
中可以添加下面一行
30 14 * * * sh /home/centos/cron-scripts/stop-ec2.sh >> /tmp/stop
这会将输出记录到 /tmp/stop
。 30 14 * * *
是您可以签入的 UTC cron 表达式 https://crontab.guru/
AWS 有一个很好的文档,解释了如何使用 Lambda 和 Cloudwatch 事件实现这一点。你可以参考它 - https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
这个解决方案可以修改为动态获取EC2列表,或者对一组可以根据特定标签识别的实例进行操作。
亚马逊最近(2018 年 2 月)发布了 EC2 实例调度程序工具:
The AWS Instance Scheduler is a simple AWS-provided solution that
enables customers to easily configure custom start and stop schedules
for their Amazon Elastic Compute Cloud (Amazon EC2) and Amazon
Relational Database Service (Amazon RDS) instances. The solution is
easy to deploy and can help reduce operational costs for both
development and production environments. Customers who use this
solution to run instances during regular business hours can save up to
70% compared to running those instances 24 hours a day.
我在 15 分钟内将其设置并 运行 存入我的帐户;使用起来非常简单,而且几乎免费。
https://aws.amazon.com/answers/infrastructure-management/instance-scheduler/
用于停止实例的 Lambda 脚本:
import json
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
filter = [{'Name': 'tag:Name', 'Values': ['****-env']}] //give instance name here in place of ****-env
instances = ec2.describe_instances(Filters=filter)
#ec2.stop_instances(InstanceIds=instances)
stop_instance = instances.get('Reservations')[0].get('Instances')[0].get('InstanceId')
stop_instances = []
stop_instances.append(stop_instance)
ec2.stop_instances(InstanceIds=stop_instances)
启动实例的 Lambda 脚本:
import json
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
filter = [{'Name': 'tag:Name', 'Values': ['****-env']}]
instances = ec2.describe_instances(Filters=filter)
#ec2.stop_instances(InstanceIds=instances)
start_instance = instances.get('Reservations')[0].get('Instances')[0].get('InstanceId')
start_instances = []
start_instances.append(start_instance)
ec2.start_instances(InstanceIds=start_instances)
如果您使用 ASG,ASG 调度程序是管理 EC2 实例的最佳和最简单的选择。如果不使用 ASG,那么您可以使用 AWS 实例调度程序 CF 解决方案或带有 cloudwatch Cron 事件的 lambda。
我是使用 AWS 的初学者。
我只是想定期自动停止和启动几个 EC2 实例(不重启)。
有推荐的方法吗?
是的,您可以使用 AWS Lambda 做到这一点。您可以 select Cloudwatch 中的触发器,它 运行 在 UTC 上的 Cron 表达式上。
这里是相关的linkhttps://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
另一种选择是使用 awscli
,可从 pip
、apt-get
、yum
或 brew
获得,然后使用 运行使用您来自 IAM 的凭据连接 aws configure
并执行以下 bash 脚本,以停止标记有 Name: Appname
和 Value: Appname Prod
的 EC2。您可以使用 awscli
标记您的实例或从 AWS 控制台手动标记它。 aws ec2 stop-instances
将停止实例,jq
用于过滤 json 查询并使用来自 aws ec2 describe-instances
.
验证 aws configure
是否成功并且 returns json 输出 运行 aws ec2 describe-instances
和你的 运行ning 实例 ID 应该在那里在输出中。这是一个示例输出
{
"Reservations": [
{
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-xxx.ap-south-1.compute.amazonaws.com",
"State": {
"Code": xx,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "20xx-xx-xxTxx:16:xx.000Z",
"PublicIpAddress": "xx.127.24.xxx",
"PrivateIpAddress": "xxx.31.3.xxx",
"ProductCodes": [],
"VpcId": "vpc-aaxxxxx",
"StateTransitionReason": "",
"InstanceId": "i-xxxxxxxx",
"ImageId": "ami-xxxxxxx",
"PrivateDnsName": "ip-xxxx.ap-south-1.compute.internal",
"KeyName": "node",
"SecurityGroups": [
{
"GroupName": "xxxxxx",
"GroupId": "sg-xxxx"
}
],
"ClientToken": "",
"SubnetId": "subnet-xxxx",
"InstanceType": "t2.xxxxx",
"NetworkInterfaces": [
{
"Status": "in-use",
"MacAddress": "0x:xx:xx:xx:xx:xx",
"SourceDestCheck": true,
"VpcId": "vpc-xxxxxx",
"Description": "",
"NetworkInterfaceId": "eni-xxxx",
"PrivateIpAddresses": [
{
"PrivateDnsName": "ip-xx.ap-south-1.compute.internal",
"PrivateIpAddress": "xx.31.3.xxx",
"Primary": true,
"Association": {
"PublicIp": "xx.127.24.xxx",
"PublicDnsName": "ec2-xx.ap-south-1.compute.amazonaws.com",
"IpOwnerId": "xxxxx"
}
}
],
"PrivateDnsName": "ip-xxx-31-3-xxx.ap-south-1.compute.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "xxx",
"AttachTime": "20xx-xx-30Txx:16:xx.000Z"
},
"Groups": [
{
"GroupName": "xxxx",
"GroupId": "sg-xxxxx"
}
],
"Ipv6Addresses": [],
"OwnerId": "xxxx",
"PrivateIpAddress": "xx.xx.xx.xxx",
"SubnetId": "subnet-xx",
"Association": {
"PublicIp": "xx.xx.xx.xxx",
"PublicDnsName": "ec2-xx.ap-south-1.compute.amazonaws.com",
"IpOwnerId": "xxxx"
}
}
],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": "",
"AvailabilityZone": "xx"
},
"Hypervisor": "xxx",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xxx",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-xxx",
"AttachTime": "20xxx-xx-xxTxx:16:xx.000Z"
}
}
],
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/xxx",
"VirtualizationType": "xxx",
"Tags": [
{
"Value": "xxxx centxx",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
],
"ReservationId": "r-xxxx",
"Groups": [],
"OwnerId": "xxxxx"
}
]
}
下面的bash脚本是stop-ec2.sh
在/home/centos/cron-scripts/
(instance=$(aws ec2 describe-instances | jq '.Reservations[].Instances | select(.[].Tags[].Value | startswith("Appname Prod") ) | select(.[].Tags[].Key == "Appname") | {InstanceId: .[].InstanceId, PublicDnsName: .[].PublicDnsName, State: .[].State, LaunchTime: .[].LaunchTime, Tags: .[].Tags} | [.]' | jq -r .[].InstanceId) && aws ec2 stop-instances --instance-ids ${instance} )
运行 使用 sh /home/centos/cron-scripts/stop-ec2.sh
的文件并验证 EC2 实例是否已停止。调试 运行 aws ec2 describe-instances | jq '.Reservations[].Instances | select(.[].Tags[].Value | startswith("Appname Prod") ) | select(.[].Tags[].Key == "Appname") | {InstanceId: .[].InstanceId, PublicDnsName: .[].PublicDnsName, State: .[].State, LaunchTime: .[].LaunchTime, Tags: .[].Tags} | [.]' | jq -r .[].InstanceId
并查看它 returns 已标记的正确实例 ID。
然后在crontab -e
中可以添加下面一行
30 14 * * * sh /home/centos/cron-scripts/stop-ec2.sh >> /tmp/stop
这会将输出记录到 /tmp/stop
。 30 14 * * *
是您可以签入的 UTC cron 表达式 https://crontab.guru/
AWS 有一个很好的文档,解释了如何使用 Lambda 和 Cloudwatch 事件实现这一点。你可以参考它 - https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
这个解决方案可以修改为动态获取EC2列表,或者对一组可以根据特定标签识别的实例进行操作。
亚马逊最近(2018 年 2 月)发布了 EC2 实例调度程序工具:
The AWS Instance Scheduler is a simple AWS-provided solution that enables customers to easily configure custom start and stop schedules for their Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Relational Database Service (Amazon RDS) instances. The solution is easy to deploy and can help reduce operational costs for both development and production environments. Customers who use this solution to run instances during regular business hours can save up to 70% compared to running those instances 24 hours a day.
我在 15 分钟内将其设置并 运行 存入我的帐户;使用起来非常简单,而且几乎免费。
https://aws.amazon.com/answers/infrastructure-management/instance-scheduler/
用于停止实例的 Lambda 脚本:
import json
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
filter = [{'Name': 'tag:Name', 'Values': ['****-env']}] //give instance name here in place of ****-env
instances = ec2.describe_instances(Filters=filter)
#ec2.stop_instances(InstanceIds=instances)
stop_instance = instances.get('Reservations')[0].get('Instances')[0].get('InstanceId')
stop_instances = []
stop_instances.append(stop_instance)
ec2.stop_instances(InstanceIds=stop_instances)
启动实例的 Lambda 脚本:
import json
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
filter = [{'Name': 'tag:Name', 'Values': ['****-env']}]
instances = ec2.describe_instances(Filters=filter)
#ec2.stop_instances(InstanceIds=instances)
start_instance = instances.get('Reservations')[0].get('Instances')[0].get('InstanceId')
start_instances = []
start_instances.append(start_instance)
ec2.start_instances(InstanceIds=start_instances)
如果您使用 ASG,ASG 调度程序是管理 EC2 实例的最佳和最简单的选择。如果不使用 ASG,那么您可以使用 AWS 实例调度程序 CF 解决方案或带有 cloudwatch Cron 事件的 lambda。