FindInstanceInProfile.py 2.0 KB

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