Skip to content

Instantly share code, notes, and snippets.

@gene1wood
Last active April 25, 2023 17:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gene1wood/5299969edc4ef21d8efcfea52158dd40 to your computer and use it in GitHub Desktop.
Save gene1wood/5299969edc4ef21d8efcfea52158dd40 to your computer and use it in GitHub Desktop.
Parse an AWS ARN (Amazon Resource Name) into it's constituent elements
def parse_arn(arn):
# http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
elements = arn.split(':')
result = {'arn': elements[0],
'partition': elements[1],
'service': elements[2],
'region': elements[3],
'account': elements[4]
}
if len(elements) == 7:
result['resourcetype'], result['resource'] = elements[5:]
elif '/' not in elements[5]:
result['resource'] = elements[5]
result['resourcetype'] = None
else:
result['resourcetype'], result['resource'] = elements[5].split('/')
return result
@canburak
Copy link

This will parse at least rds auto snapshots' arns. they have ":" in the resource

@jaytaylor
Copy link

I've created a similar library package for Go called awsarn, hope you don't mind too much if I leave a breadcrumb trail here :)

@afosterw
Copy link

afosterw commented Feb 14, 2018

Fixed version to handle resource types and resources correctly.

def parse_arn(arn):
    # http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
    elements = arn.split(':', 5)
    result = {
        'arn': elements[0],
        'partition': elements[1],
        'service': elements[2],
        'region': elements[3],
        'account': elements[4],
        'resource': elements[5],
        'resource_type': None
    }
    if '/' in result['resource']:
        result['resource_type'], result['resource'] = result['resource'].split('/',1)
    elif ':' in result['resource']:
        result['resource_type'], result['resource'] = result['resource'].split(':',1)
    return result

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