Boto - AWS SNS how to extract topic's ARN number

戏子无情 提交于 2019-12-14 01:59:58

问题


When creating a AWS SNS topic:

a = conn.create_topic(topicname)

or getting the topic already created:

a = conn.get_all_topics()

the result is:

{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'}}}

The question is how do you get topic's ARN as string: arn:aws:sns:eu-west-1:467741034465:exampletopic ?


回答1:


When you create a new topic, boto returns a Python dictionary with the data you describe above. To get the topic ARN as a string, simply reference that key in the dictionary like this:

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

it's kind of clunky but it works.

The list_topics call returns a different structure, basically like this:

{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'}}}

In this case, if you wanted to get the ARN of the first topic you would use:

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



回答2:


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])


来源:https://stackoverflow.com/questions/26656286/boto-aws-sns-how-to-extract-topics-arn-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!