Boto - AWS SNS如何提取主题的ARN号码

时间:2014-10-30 14:55:25

标签: python amazon-web-services boto amazon-sns

创建AWS SNS主题时:

a = conn.create_topic(topicname)

或者已经创建了主题:

a = conn.get_all_topics()

结果是:

{u'CreateTopicResponse': {u'ResponseMetadata': {u'RequestId': u'42b46710-degf-52e6-7d86-2ahc8e1c738c'}, u'CreateTopicResult': {u'TopicArn': u'arn:aws:sns:eu-west-1:467741034465:exampletopic'}}}

问题是如何将主题的ARN作为字符串:arn:aws:sns:eu-west-1:467741034465:exampletopic

2 个答案:

答案 0 :(得分:6)

import boto

def get_account_id():
    # suggested by https://groups.google.com/forum/#!topic/boto-users/QhASXlNBm40
    return boto.connect_iam().get_user().arn.split(':')[4]

def topic_arn_from_name(self, region, name):
    return ":".join(["arn", "aws", "sns", region, get_account_id(), name])

答案 1 :(得分:4)

当您创建新主题时,boto将返回包含您在上面描述的数据的Python字典。要将主题ARN作为字符串,只需在字典中引用该键,如下所示:

a = conn.create_topic(topicname)
a_arn = a['CreateTopicResponse']['CreateTopicResult']['TopicArn']

它有点笨重,但它有效。

list_topics调用返回不同的结构,基本上是这样的:

{u'ListTopicsResponse':
  {u'ListTopicsResult':
    {u'NextToken': None,
     u'Topics': [
      {u'TopicArn': u'arn:aws:sns:us-east-1:467741034465:exampletopic'},
      {u'TopicArn': u'arn:aws:sns:us-east-1:467741034465:footopic'}
     ]
    },
  u'ResponseMetadata': {u'RequestId': u'aef821f6-d595-55e1-af14-6d3a8064536a'}}}

在这种情况下,如果您想获得第一个主题的ARN,您将使用:

a = conn.list_topics()
a_arn = a['ListTopicsResponse']['ListTopicsResult']['Topics'][0]['TopicArn']