FindInstanceInProfile.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. FOUND=FOUND+1
  60. if DEBUG >= 2:
  61. print("FOUND in profile '" + PROFILE + "', Region: '" + region + "'")
  62. if FOUND > 1:
  63. FOUNDSTR = FOUNDSTR + "\n"
  64. for r in instance['Reservations']:
  65. for i in r['Instances']:
  66. FOUNDSTR = "FOUND\t" + PROFILE + "\t" + region + "\t" + i['InstanceId']
  67. # End of for region
  68. if DEBUG == 1:
  69. print(".")
  70. sys.stdout.flush()
  71. if DEBUG >= 2:
  72. print("Found " + str(FOUND) + " instances.")
  73. if FOUND > 0:
  74. print(FOUNDSTR)
  75. exit(0)
  76. else:
  77. if DEBUG == 1:
  78. print("notfound")
  79. exit(255)