簡體   English   中英

AWS:通過boto3訂閱SNS時清空SQS隊列

[英]AWS: empty SQS queue when subscribed to SNS via boto3

通過boto3訂閱SNS主題時,我在SQS隊列中沒有收到任何消息。

這是我使用的代碼或API憑據的問題嗎? 與此帳戶關聯的IAM策略具有AWS PowerUser權限,這意味着它具有對管理SNS主題和SQS隊列的無限制訪問權限。

當我通過AWS控制台(創建主題,創建隊列,訂閱隊列到主題)創建等效結構並使用boto3,AWS CLI或AWS控制台發送消息時,消息正確顯示。

我不認為這是代碼的問題,因為正確返回了SubscriptionArn

我在US-EAST-1和AP-SE-1地區嘗試了這個,結果相同。

示例代碼:

#!/usr/bin/env python3

import boto3
import json

def get_sqs_msgs_from_sns():
    sqs_client = boto3.client('sqs', region_name='us-east-1')
    sqs_obj = boto3.resource('sqs', region_name='us-east-1')
    sns_client = boto3.client('sns', region_name='us-east-1')
    sqs_queue_name = 'queue1'
    topic_name = 'topic1'

    # Create/Get Queue
    sqs_client.create_queue(QueueName=sqs_queue_name)
    sqs_queue = sqs_obj.get_queue_by_name(QueueName=sqs_queue_name)
    queue_url = sqs_client.get_queue_url(QueueName=sqs_queue_name)['QueueUrl']
    sqs_queue_attrs = sqs_client.get_queue_attributes(QueueUrl=queue_url,
                                                    AttributeNames=['All'])['Attributes']
    sqs_queue_arn = sqs_queue_attrs['QueueArn']
    if ':sqs.' in sqs_queue_arn:
        sqs_queue_arn = sqs_queue_arn.replace(':sqs.', ':')

    # Create SNS Topic
    topic_res = sns_client.create_topic(Name=topic_name)
    sns_topic_arn = topic_res['TopicArn']

    # Subscribe SQS queue to SNS
    sns_client.subscribe(
            TopicArn=sns_topic_arn,
            Protocol='sqs',
            Endpoint=sqs_queue_arn
    )

    # Publish SNS Messages
    test_msg = {'default': {"x":"foo","y":"bar"}}
    test_msg_body = json.dumps(test_msg)
    sns_client.publish(
        TopicArn=sns_topic_arn, 
        Message=json.dumps({'default': test_msg_body}),
        MessageStructure='json')

    # Validate Message
    sqs_msgs = sqs_queue.receive_messages(
            AttributeNames=['All'],
            MessageAttributeNames=['All'],
            VisibilityTimeout=15,
            WaitTimeSeconds=20,
            MaxNumberOfMessages=5
    )
    assert len(sqs_msgs) == 1
    assert sqs_msgs[0].body == test_msg_body
    print(sqs_msgs[0].body) # This should output dict with keys Message, Type, Timestamp, etc., but only returns the test_msg

if __name__ == "__main__":
    get_mock_sqs_msgs_from_sns()

我收到這個輸出:

$ python .\sns-test.py
Traceback (most recent call last):
  File ".\sns-test.py", line 55, in <module>
    get_sqs_msgs_from_sns()
  File ".\sns-test.py", line 50, in get_sqs_msgs_from_sns
    assert len(sqs_msgs) == 1
AssertionError

上面針對C#AWS SDK提出的類似問題的URL讓我正確地指出了這個問題:我需要將策略附加到SQS隊列以允許SNS主題寫入它。

def allow_sns_to_write_to_sqs(topicarn, queuearn):
    policy_document = """{{
  "Version":"2012-10-17",
  "Statement":[
    {{
      "Sid":"MyPolicy",
      "Effect":"Allow",
      "Principal" : {{"AWS" : "*"}},
      "Action":"SQS:SendMessage",
      "Resource": "{}",
      "Condition":{{
        "ArnEquals":{{
          "aws:SourceArn": "{}"
        }}
      }}
    }}
  ]
}}""".format(queuearn, topicarn)

    return policy_document

policy_json = allow_sns_to_write_to_sqs(topic_arn, queue_arn)

response = sqs_client.set_queue_attributes(
    QueueUrl = queue_url,
    Attributes = {
        'Policy' : policy_json
    }
)
print(response)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM