In my application i need to send messages to the given topic name. The topic is already created by other person and in a config file they give only the topic Name. My work is to push the messages in the given topic Name. Is there any way to get topic ARN by topic NAME in java?
5 Answers
As stated in this answer using createTopic(topicName) is more direct approach. In case topic have been created before, it will just return you topic ARN.
-
I think this is a best answer for this question! – harley Feb 17 '19 at 16:14
-
Although the answer is technically correct, it does not follow the principle of least privilege. If you want to follow this, you should better go through the list of topics or create the ARN according to the pattern. – Tobias Stangl May 16 '23 at 06:25
I've done this one of two ways. The ARN is always the same pattern. So, you could just subscribe to "arn:aws:sns:<region>:<account>:<name>" where:
region is from Regions.getCurrentRegion(). Be careful with this as it is a bit expensive of a call and you'll need to handle not being on an EC2/Elastic Beanstalk instance.
account is from AmazonIdentityManagementClient.getUser().getUser().getArn(). You'll have to parse the account number from that. Same warning about not being in an EC2 environment.
name is what you have.
A simpler way is loop through the the topics and look for the name you want in the ARN. You will use the AmazonSNSClient listTopics method to do this. Remember that that method only returns the first 100 topics - you'll want to properly loop over the entire topic list.
This might be what you need. Supply the topic and get it from available topics.
import json
import boto3
def lambda_handler(event, context):
try:
topic = event['topic']
subject = event['subject']
body = event['body']
subscriber = event['subscriber']
sns_client = boto3.client('sns')
sns_topic_arn = [tp['TopicArn'] for tp in sns_client.list_topics()['Topics'] if topic in tp['TopicArn']]
sns_client.publish(TopicArn = sns_topic_arn[0], Message=body,
Subject=subject)
except Exception as e:
print(e)

- 2,214
- 6
- 33
- 47

- 11
- 1
If you have create topic permission, you can try this: link
If you don't have permission, you can try this:
private static Optional<Topic> getTopicByName(SnsClient snsClient,
String topicName) {
for (val topicsResponse : snsClient.listTopicsPaginator()) {
if (topicsResponse.hasTopics()) {
for (val topic : topicsResponse.topics()) {
// Arn format => arn:aws:sns:region:account-id:topic-name
val arn = topic.topicArn();
val sp = arn.split(":");
if (topicName.equals(sp[sp.length - 1])) {
return Optional.of(topic);
}
}
}
}
return Optional.empty();
}

- 51
- 4
What you can do, is to create a table that contains topic and its topicArn.
The topic arn can be retrieve by the console or using the api when you create a topic.
This way no need to loop or try to match a pattern.

- 280
- 1
- 4
- 14