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('')
az ='utf-8')
f = urllib.request.urlopen('')
instance ='utf-8')
arn = 'arn:aws:ec2:' + az + ':instance/' + instance

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": [
  "detail": {
    "instance-id": "i-05493b58ebcba0c43",
    "instance-action": "terminate"
Stein van Broekhoven
Cloud & Open-Source magician 🧙‍♂️

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

comments powered by Disqus