boto3 EC2 脚本电子邮件:所有状态检查的一封电子邮件

Posted

技术标签:

【中文标题】boto3 EC2 脚本电子邮件:所有状态检查的一封电子邮件【英文标题】:boto3 EC2 script email: One email for all status checks 【发布时间】:2022-01-17 19:24:55 【问题描述】:

每个实例都收到一封未通过状态检查的电子邮件。我想为所有状态检查收到一封电子邮件。

这是我的代码:

import boto3
import smtplib

client = boto3.client("ec2")
clientsns = boto3.client("sns")

status = client.describe_instance_status(IncludeAllInstances = True)
#failed_instances = []
for i in status["InstanceStatuses"]:
#        failed_instances.append(i['Instance')]      
        in_status = i['InstanceStatus']['Details'][0]['Status']
        sys_status = i['SystemStatus']['Details'][0]['Status']
        
        # check statuses failed instances
        if ((in_status != 'passed') or (sys_status != 'passed')):
             msg = f'The following instances failed status checks, i["InstanceId"]'
             clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg)

【问题讨论】:

【参考方案1】:

试试这样的:

import boto3
import botocore
from boto3 import Session

boto3.setup_default_session(profile_name='account2')

def get_tag(tags, key='Name'):
    if not tags: return ''
    for tag in tags:
        if tag['Key'] == key:
            return tag['Value']
    return ''

client = boto3.client("ec2")
conn = boto3.resource('ec2')
#instances = conn.instances.filter()
instances = conn.instances.filter(
        Filters=['Name': 'instance-state-name', 'Values': ['running']])

filter_for = 
    "running": ["Name": "instance-state-name", "Values": ["running"]],


ec2instance = client.describe_instance_status(IncludeAllInstances = True, Filters=filter_for["running"])

failed_instances = []
for i in ec2instance["InstanceStatuses"]:    
        in_status = i['InstanceStatus']['Details'][0]['Status']
        sys_status = i['SystemStatus']['Details'][0]['Status']
        
        # check statuses failed instances
        if ((in_status != 'passed') or (sys_status != 'passed')):
             failed_instances.append(i["InstanceId"])

if len(failed_instances)>0:
 #   new_line = '\n'
 #   msg = f'The following instances failed status checks:new_line new_line.join(failed_instances)'
 #   #msg = f'The following instances failed status checks, failed_instances'
 
 #   clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg)

for j in failed_instances:
  instance = [x for x in list(instances) if x.id == j][0]
  instance_name = get_tag(instance.tags)        
  print (instance_name, instance.id, instance.instance_type) 

【讨论】:

谢谢。如何将每个实例放在不同的行上 只需使用换行符\n。查看编辑后的答案 您好,我知道如何打印出实例的 TAG 名称。标签中的键值是名称和值 查看编辑后的答案。此外,SO 中还有其他问题更详细。 这是否意味着我需要双循环?我想打印出实例名称,状态检查失败的实例 ID

以上是关于boto3 EC2 脚本电子邮件:所有状态检查的一封电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中使用 boto3 模块检查 Redshift 的集群状态?

boto3如何获取单个ec2实例的所有标签并附加新标签

我们如何使用 python boto3 获取挂载到 EC2 实例的所有文件系统(EFS)的列表?

boto3 instance.filter 数组

使用boto3 Python SDK返回AWS EC2可用性区域属性

函数 ec2.snapshots.all 不迭代 boto3 lambda