FindInstanceInProfile.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #! /usr/bin/python
  2. #
  3. # Find an instance within a profile, across all regions
  4. #
  5. # Unbuffered, no CRLF print:
  6. from __future__ import print_function
  7. import sys, os
  8. import boto3, boto3.session, botocore
  9. import threading # We may not do it yet, but developing with threadsafe in mind, as best I can
  10. try:
  11. # Python 3
  12. import builtins
  13. except ImportError:
  14. # Python 2
  15. import __builtin__ as builtins
  16. # Debug levels:
  17. # 1 = Show progress
  18. # 2 = Informational
  19. # 5 = Include boto3 logging
  20. DEBUG=0
  21. # Fancy print function to make it 3.4 compatible:
  22. if len(sys.argv) != 3:
  23. print("Usage: " + os.path.basename(sys.argv[0]) + " <profile> <searchstring>")
  24. exit(1)
  25. if DEBUG >= 5:
  26. boto3.set_stream_logger('botocore', level=DEBUG)
  27. PROFILE=sys.argv[1]
  28. SEARCHSTRING=sys.argv[2]
  29. # Set the profile to use
  30. try:
  31. boto3.setup_default_session(profile_name=PROFILE)
  32. except:
  33. print("Could not find profile: " + PROFILE)
  34. exit(2)
  35. # Connect to ec2
  36. ec2 = boto3.client('ec2')
  37. # Grab list of regions
  38. regions = set()
  39. for region in ec2.describe_regions()['Regions']:
  40. regions.add(region['RegionName'])
  41. # For each array, let's search:
  42. FOUND=0
  43. FOUNDSTR=""
  44. if DEBUG == 1:
  45. print("Searching.", end="")
  46. sys.stdout.flush()
  47. for region in regions:
  48. if DEBUG == 1:
  49. print(".", end="")
  50. sys.stdout.flush()
  51. if DEBUG >= 2:
  52. print("Searching region " + region + " in profile " + PROFILE)
  53. ec2 = boto3.client('ec2', region_name=region)
  54. try:
  55. instance = ec2.describe_instances(InstanceIds=[ SEARCHSTRING ])
  56. except botocore.exceptions.ClientError:
  57. # Not Found
  58. continue
  59. except:
  60. print(str( sys.exc_info() ))
  61. FOUND=FOUND+1
  62. if DEBUG >= 2:
  63. print("FOUND in profile '" + PROFILE + "', Region: '" + region + "'")
  64. if FOUND > 1:
  65. FOUNDSTR = FOUNDSTR + "\n"
  66. # Add to output
  67. for r in instance['Reservations']:
  68. for i in r['Instances']:
  69. FOUNDSTR = "FOUND\t" + PROFILE + "\t" + region + "\t" + i['InstanceId']
  70. # End of for region
  71. if DEBUG == 1:
  72. print(".")
  73. sys.stdout.flush()
  74. if DEBUG >= 2:
  75. print("Found " + str(FOUND) + " instances.")
  76. if FOUND > 0:
  77. print(FOUNDSTR)
  78. exit(0)
  79. else:
  80. if DEBUG == 1:
  81. print("notfound")
  82. exit(255)