Skip to content

Instantly share code, notes, and snippets.

@RulerOf
Last active January 31, 2020 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RulerOf/b9f5dd00a9911aba8271b57d3d269d7a to your computer and use it in GitHub Desktop.
Save RulerOf/b9f5dd00a9911aba8271b57d3d269d7a to your computer and use it in GitHub Desktop.
Parse an AWS ARN with Ruby

You can use this code to reliably parse an AWS ARN and get its various sections.

Paste this class into your library, or put arn_parse.rb into your project's lib folder and require it. Then you can feed it an ARN and get back an object:

require_relative 'lib/arn_parse.rb'

my_arn = Arn.parse 'arn:aws:sns:*:123456789012:my_corporate_topic'  => #<Arn:0x00007f91550a6e80 @partition="aws", @service="sns", @region="*", @account="123456789012", @resource="my_corporate_topic">
my_arn.service                                                      => "sns"
class Arn
attr_accessor :partition
attr_accessor :service
attr_accessor :region
attr_accessor :account
attr_accessor :resource
def initialize(partition, service, region, account, resource)
@partition = partition
@service = service
@region = region
@account = account
@resource = resource
end
def self.parse(arn)
raise TypeError, 'ARN must be supplied as a string' unless arn.is_a?(String)
arn_components = arn.split(':', 6)
raise ArgumentError, 'Could not parse ARN' if arn_components.length < 6
Arn.new arn_components[1],
arn_components[2],
arn_components[3],
arn_components[4],
arn_components[5]
end
end
@endymion
Copy link

Thanks, Andrew! I packaged this as a gem: https://github.com/endymion/arn_parse

@RulerOf
Copy link
Author

RulerOf commented Dec 19, 2019

I hope you find it useful! Beware that I did find some arns later that didn't... reliably fit into this parsing scheme. You can end up with arn.resource strings that contain colons.

I don't know whether or not it's always valid, but I was pretty convinced when I wrote the class :)

@dblock
Copy link

dblock commented Jan 31, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment