本文记录使用Python
脚本和Boto3
按名字搜索AWS Image
并返回AWS Image
的相关参数。
记得操作之前拿到相应的权限:
export AWS_ACCESS_KEY_ID="xxxxxxxxxxxxxxxxxxxxxxxxxx"
export AWS_SECRET_ACCESS_KEY="yyyyyyyyyyyyyyyyyyyyyyyyyyyy"
export AWS_SESSION_TOKEN="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
使用以下Python脚本:
#!/bin/python
import json
import boto3
def get_ec2_image():
ec2_client = boto3.client('ec2')
describe_images_response = ec2_client.describe_images(
DryRun=False,
Owners=[
'amazon',
],
Filters=[
{
'Name': 'name',
'Values': [
'amzn2-ami-ecs-hvm-2.0.20231204-x86_64-ebs',
]
},
]
)
print("image return: "+ json.dumps(describe_images_response, indent = 4))
以上函数会返回镜像的相关参数,例如使用ImageId来用于创建EC2资源,以下的返回为"ImageId": "ami-0b00532b21d4d18e4"
为了让Json输出更美观,使用了indent = 4
这个参数,显示效果如下:
image return: {
"Images": [
{
"Architecture": "x86_64",
"CreationDate": "2023-12-04T21:56:34.000Z",
"ImageId": "ami-0b00532b21d4d18e4",
"ImageLocation": "amazon/amzn2-ami-ecs-hvm-2.0.20231204-x86_64-ebs",
"ImageType": "machine",
"Public": true,
"OwnerId": "591542846629",
"PlatformDetails": "Linux/UNIX",
"UsageOperation": "RunInstances",
"State": "available",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": {
"DeleteOnTermination": true,
"SnapshotId": "snap-0308eecd299954d62",
"VolumeSize": 30,
"VolumeType": "gp2",
"Encrypted": false
}
}
],
"Description": "Amazon Linux AMI 2.0.20231204 x86_64 ECS HVM GP2",
"EnaSupport": true,
"Hypervisor": "xen",
"ImageOwnerAlias": "amazon",
"Name": "amzn2-ami-ecs-hvm-2.0.20231204-x86_64-ebs",
"RootDeviceName": "/dev/xvda",
"RootDeviceType": "ebs",
"SriovNetSupport": "simple",
"VirtualizationType": "hvm",
"DeprecationTime": "2025-12-04T21:56:34.000Z"
}
],
"ResponseMetadata": {
"RequestId": "d7c02b8d-c2f8-49eb-8e45-a897b32d3a7e",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"x-amzn-requestid": "d7c02b8d-c2f8-49eb-8e45-a897b32d3a7e",
"cache-control": "no-cache, no-store",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"content-type": "text/xml;charset=UTF-8",
"content-length": "1926",
"date": "Tue, 19 Dec 2023 14:37:16 GMT",
"server": "AmazonEC2"
},
"RetryAttempts": 0
}
}