![](/img/trans.png)
[英]How can I get the SNS topic ARN using the topic name to publish a SNS message in Python via Boto3?
[英]To get the SNS Topic name from the SNS Topic ARN using python
我正在編寫一個 boto3 腳本,我必須按名稱列出 sns 主題,但問題是現在我認為get_topic_name()
API 沒有到位,當我嘗試此method(function)
時出現錯誤。 現在 output 以arn:aws:{region}:{account_number}:{topic_name} arn:aws:ca-central-1:111122223333:sns-test-topic
形式出現有人可以告訴如何只獲取名稱嗎?
這是代碼: -
import boto3
from pprint import pprint
account_id = input("Enter the AWS account Id:")
regions = ['ap-northeast-1', 'ap-southeast-1',
'ca-central-1', 'us-east-1', 'us-east-2']
for region in regions:
session = boto3.session.Session()
client = session.client('sns', region_name=region)
for arn in client.list_topics()['Topics']:
print(arn['TopicArn'])
Split 會將 str 轉換為單詞列表,然后使用循環提取名稱。
import boto3
from pprint import pprint
account_id = input("Enter the AWS account Id:")
regions = ['ap-northeast-1', 'ap-southeast-1',
'ca-central-1', 'us-east-1', 'us-east-2']
list_arn_name = []
for region in regions:
session = boto3.session.Session()
client = session.client('sns', region_name=region)
for arn in client.list_topics()['Topics']:
list_arn_name.append(arn['TopicArn'].split(':'))
for each in list_arn_name:
print(each[5])
由於主題名稱始終是 ARN 的最后一個字段,因此您可以使用 rsplit 提取它們:
print(arn['TopicArn'].rsplit(':',1)[1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.