Search code examples
powershellamazon-web-servicesamazon-snsaws-powershell

AWS Powershell - Get SNS TOPIC by name


I can't find a way to retreive the SNS topic by name other than doing the following on an already created topic:

$topicarn = New-SNSTopic -Name "$deployedAppVersion-$environment-Events"

The problem with the above is if I get the $deployedAppVersion wrong It's going to create an SNS topic where it shouldn't.

I've looked for a "Get-SNSTopic" but I don't think it exists. The only alternative to what I've got that I can see is a big dirty list of all the topics and searching it for the arn that contains the name I want.

Is there a better way?


Solution

  • Get-SNSTopic does exist, but it looks like it maps to the list topics API and simply returns a list of ARNs -- the behavior that you've described. The API and CLI seem to have similar limitations.

    You could functionally get what you want by wrapping Get-SNSTopicAttribute to split the arn into parts:

    Function Get-SNSTopicByName
    {
        param
        (
            [string]$Region = 'us-east-1',
            [string]$AWSAccountNumber = '123456781234',
            [string]$TopicName
        )
    
        $topicArn = "arn:aws:sns:$($Region):$($AWSAccountNumber):$($TopicName)"
    
        Get-SNSTopicAttribute -TopicArn $topicArn
    }
    
    Get-SNSTopicByName -TopicName "my-topic"
    

    Get-SNSTopicAttribute returns a Dictionary<string, string> of useful information about the topic, and will also error out if that topic doesn't exist. This seems closer to what you what.

    You can get individual parts by accessing via key:

    PS C:/> $result = Get-SNSTopicByName -TopicName "my-topic"
    PS C:/> $result["TopicArn"]
    arn:aws:sns:us-east-1:123456781234:my-topic
    PS C:/> $result["DisplayName"]
    My Test Topic (Dev)