Get ec2 arn for local ec2 machine with python

A super minimal urllib based arn constructor based on local metadata

import urllib.request

# local ec2 arn:
f = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/placement/availability-zone')
az = f.read().decode('utf-8')
f = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id')
instance = f.read().decode('utf-8')
arn = 'arn:aws:ec2:' + az + ':instance/' + instance
print(arn)

This returns arn as used by the EC2 Spot Instance Interruption Warning event

{
  "version": "0",
  "id": "03a51c99-95cb-c6e8-03a8-3ce3ac402d64",
  "detail-type": "EC2 Spot Instance Interruption Warning",
  "source": "aws.ec2",
  "account": "763603311319",
  "time": "2018-09-16T13:17:10Z",
  "region": "eu-west-1",
  "resources": [
    "arn:aws:ec2:eu-west-1b:instance/i-05493b58ebcba0c43"
  ],
  "detail": {
    "instance-id": "i-05493b58ebcba0c43",
    "instance-action": "terminate"
  }
}
Cloud & Open-Source magician 🧙‍♂️

I try to find the KISS in complex systems and share it with the world.

comments powered by Disqus