基于标签的 Grepping EC2 实例 ID
Grepping EC2 Instance IDs based on Tag
要求
对于 EC2 实例,如果特定实例的名称标签为空或标签本身不存在,我想显示实例 ID。
对于所有 EC2 实例,如果 Schedule 标签仅具有以下值。除此之外的任何值都应显示实例 ID。
允许的值:
- 是
- 是
- 没有
- 没有
我尝试了这些命令:
aws ec2 describe-instances --instance-ids "${line}"| jq -r '.Reservations[].Instances[].Tags[].Key'|grep Schedule` ]] || echo $line >> without_id.txt
aws ec2 describe-instances --instance-ids "${line}"| jq -r '.Reservations[].Instances[].Tags[].Key'|grep Name` ]] || echo $line
您的要求对于命令行工具来说有点太难了。
相反,我建议使用 Python 脚本:
import boto3
ec2_resource = boto3.resource('ec2')
# Show Instance ID if there is no Name tag, or the Name tag is empty
for instance in ec2_resource.instances.all():
name_tags = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name']
if len(name_tags) == 0:
print('No name tag:', instance.id)
elif name_tags[0] == '':
print('Empty name tag:', instance.id)
# Show Instance ID if the Schedule tag is not Yes or No
for instance in ec2_resource.instances.all():
schedule_tags = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Schedule']
if schedule_tags and schedule_tags[0] not in ['Yes', 'yes', 'No', 'no']:
print('Bad schedule tag:', instance.id, schedule_tags[0])
要求
对于 EC2 实例,如果特定实例的名称标签为空或标签本身不存在,我想显示实例 ID。
对于所有 EC2 实例,如果 Schedule 标签仅具有以下值。除此之外的任何值都应显示实例 ID。
允许的值:
- 是
- 是
- 没有
- 没有
我尝试了这些命令:
aws ec2 describe-instances --instance-ids "${line}"| jq -r '.Reservations[].Instances[].Tags[].Key'|grep Schedule` ]] || echo $line >> without_id.txt
aws ec2 describe-instances --instance-ids "${line}"| jq -r '.Reservations[].Instances[].Tags[].Key'|grep Name` ]] || echo $line
您的要求对于命令行工具来说有点太难了。
相反,我建议使用 Python 脚本:
import boto3
ec2_resource = boto3.resource('ec2')
# Show Instance ID if there is no Name tag, or the Name tag is empty
for instance in ec2_resource.instances.all():
name_tags = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name']
if len(name_tags) == 0:
print('No name tag:', instance.id)
elif name_tags[0] == '':
print('Empty name tag:', instance.id)
# Show Instance ID if the Schedule tag is not Yes or No
for instance in ec2_resource.instances.all():
schedule_tags = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Schedule']
if schedule_tags and schedule_tags[0] not in ['Yes', 'yes', 'No', 'no']:
print('Bad schedule tag:', instance.id, schedule_tags[0])