使用 Windows Server 2016 实例。
我希望实例在终止之前运行本地命令。
我可以在 Windows 关闭时运行脚本。
我希望脚本检查实例本身是否处于终止状态,如果是,则运行一些清理操作。
从文档中不确定,有没有办法从实例本身检查本地实例是否正在终止? https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories
这将返回 InstanceStatuses:
aws ec2 describe-instance-status --include-all-instances --instance-ids i-123123123
看起来像:
{
"InstanceStatuses": [
{
"AvailabilityZone": "us-west-2a",
"InstanceId": "i-123123123",
"InstanceState": {
"Code": 16,
"Name": "running"
},
"InstanceStatus": {
"Details": [
{
"Name": "reachability",
"Status": "passed"
}
],
"Status": "ok"
},
"SystemStatus": {
"Details": [
{
"Name": "reachability",
"Status": "passed"
}
],
"Status": "ok"
}
}
]
}
实例“终止”时的状态是什么样的?尚未终止但处于待终止状态?如何检查实例是否处于待终止状态?
答案1
您所说的terminating state
AWS 指的是shutting-down
。
您可以使用describe-instances
并使用--query
或jq
来解析出您想要的信息。
--query 示例:
aws ec2 describe-instances --instance-ids i-070ca5c669933b949 --query 'Reservations[].Instances[].State.Code
将返回实例状态代码(详细信息如下):
[48]
jq 示例:
aws ec2 describe-instances --instance-ids i-070ca5c669933b949 |jq .Reservations[].Instances[].State.Code
输出:
四十八
您还可以以文本形式获取输出:
aws ec2 describe-instances --instance-ids i-070ca5c669933b949 |jq .Reservations[].Instances[].State.Name
将会输出:
“终止”
以下是命令的相关输出和与实例状态相对应的代码:
State -> (structure)
The current state of the instance.
Code -> (integer)
The low byte represents the state. The high byte is used for internal purposes and should be ignored.
0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
Name -> (string)
The current state of the instance.
参考
https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html