Search code examples
c#amazon-web-servicesamazon-sqs

Getting SQS queue name or URL from ARN, or check a queue exists by ARN


The AWS documentation states consistently that ARNs should not be constructed programmatically from names or URLs, because the way those strings are constructed is not guaranteed to be constant in time.

My issue is that, on SQS, the RedrivePolicy attribute returned by GetQueueAttributes references the dead-letter queue by ARN only.

I am currently writing a service to create queues and set them up, or verify that their setup is correct if they already exist. But I don't see the way I can verify that the dead-letter queue ARN matches an existing queue, unless I do parse it to get the name. Is there a way around that?

(actually to be fair, there is one way that respects the "don't parse ARNs programmatically" rule, which consists in calling ListQueues then loop through the resulting URLs calling GetQueueAttributes on each, but that sounds like a silly amount of work, and could potentially fail if there are more than 1000 queues on the account, so I'm excluding doing this).

Currently looking for a solution in C# but the issue is not language-dependent.


Solution

  • In C#, there is a parser class in the AWSSDK.Core package called Amazon.Arn.

    It was seemingly added around version 3.3.104 of the package in Dec '19 (Source here). So even though ARNs aren't meant to be constructed programmatically, this seems to be setting the format in stone.

    Now to get the name, knowing that the ARN is that of a queue, one can do Arn.Parse(queueArn).Resource.

    Conversely, one can create a new Arn object then call ToString() on it to get the full ARN.

    This of course can be improved for a random ARN (The Arn object contains more information than the resource sur as the service), and will not work as is for any resource type (e.g. Resource would return queue-name:some-guid for an SQS subscription, or rule/rule-name for an EventBridge rule.

    More information can be found about ARNs here.