-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在評論