-1

我想编写下面的Python脚本作为Amazon lambda函数,该脚本将RabbitMQ指标发布到Amazon cloudwatch,我尝试了几次并尝试获取rabbitmq深度,但是我的Lambda函数未能将度量指标发布到cloudwatch。如何将Python脚本编写为Amazon Lambda函数?

from __future__ import with_statement, print_function 
from pyrabbit.api import Client 
import boto3 
import os 

host = "" 
username = "" 
password = "" 
vhost = "" 
namespace = "" 

def get_queue_depths(host, username, password, vhost): 
    cl = Client(host, username, password) 
    if not cl.is_alive(): 
     raise Exception("Failed to connect to rabbitmq") 
    depths = {} 
    queues = [q['name'] for q in cl.get_queues(vhost=vhost)] 
    for queue in queues: 
     if queue == "aliveness-test": 
      continue 
     if 'celery' in queue: 
      continue 
     depths[queue] = cl.get_queue_depth(vhost, queue) 
    return depths 

def publish_queue_depth_to_cloudwatch(cwc, queue_name, depth, namespace): 
    float(depth) 
    cwc = boto3.client('cloudwatch',region_name="us-east-1") 
    response = client.put_metric_data(
     Namespace=namespace, 
     MetricData=[ { 'MetricName': queue_name, 'Value': depth, 'Unit': 'Count' } ] 
) 
print("Putting metric namespace=%s name=%s unit=Count value=%f" % 
    (namespace, queue_name, depth)) 

def publish_depths_to_cloudwatch(depths, namespace): 
    for queue in depths: 
     publish_queue_depth_to_cloudwatch(cwc, queue, depths[queue], namespace) 

def get_queue_depths_and_publish_to_cloudwatch(host, username, password, vhost, namespace): 
    depths = get_queue_depths(host, username, password, vhost) 
    publish_depths_to_cloudwatch(depths, namespace) 

if __name__ == "__main__": 
    while True: 
     get_queue_depths_and_publish_to_cloudwatch(host, username, password, vhost, namespace) 
+0

中所暗示的那么具体问题是关于从您的Lambda函数发布到CloudWatch的具体问题?当Lambda函数的CloudWatch日志无法将度量标准发布到CloudWatch时,错误消息是什么? Lambda函数是在VPC的内部还是外部运行?您是否已将适当的IAM角色分配给允许其将度量标准发布到CloudWatch的函数? –

+0

以及我的lambda函数设法获取rabbitmq深度,我可以在日志中看到它们,但是当涉及到发布到cloudwatch时,它会失败并以超时退出,函数在VPC中运行,并且是的,我将正确的IAM角色分配给功能 –

+0

如果它正在VPC中运行,那么您将不得不向VPC添加NAT网关,以便Lambda函数能够访问VPC之外的任何内容,包括AWS资源(如CloudWatch)。 –

回答

1

问题通过向VPC添加NAT网关解决,以便让lambda函数访问Aws资源。正如Mark B在评论