FindInstance.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #! /usr/bin/python
  2. #
  3. # Find an instance amongst all profile configured. Note that it makes multiple calls
  4. # to the FindInstanceInProfile.py in parallel.
  5. #
  6. # Unbuffered, no CRLF print:
  7. from __future__ import print_function
  8. import re, sys, os, subprocess
  9. import boto3
  10. import boto3.session
  11. import threading # We may not do it yet, but developing with threadsafe in mind, as best I can
  12. try:
  13. # Python 3
  14. import builtins
  15. except ImportError:
  16. # Python 2
  17. import __builtin__ as builtins
  18. # Debug levels:
  19. # 1 = Show progress
  20. # 2 = Informational
  21. # 5 = Include boto3 logging
  22. DEBUG=0
  23. if len(sys.argv) != 2:
  24. print("Usage: " + os.path.basename(sys.argv[0]) + " <searchstring>")
  25. exit(1)
  26. SEARCHSTRING=sys.argv[1]
  27. # Load profiles
  28. try:
  29. cfile = open(os.path.expanduser("~") + "/.aws/credentials", "r")
  30. except:
  31. print("You must have a ~/.aws/credentials file with profiles configured.")
  32. exit(3)
  33. profiles = set()
  34. for line in cfile:
  35. profile = re.match('^\[(.+)\]', line)
  36. if(profile):
  37. profiles.add(profile.group(1))
  38. # End of for line
  39. FOUND=0
  40. processes = set()
  41. for profile in profiles:
  42. if DEBUG >= 2:
  43. print("Searching profile " + profile)
  44. # returncode = subprocess.call(['FindInstanceInProfile.py', profile, SEARCHSTRING])
  45. process = subprocess.Popen(['FindInstanceInProfile.py', profile, SEARCHSTRING])
  46. if DEBUG >= 2:
  47. print("PID = " + str(process.pid))
  48. processes.add(process)
  49. # We should have spawned all child processes. Let's wait for them.
  50. for process in processes:
  51. if DEBUG >= 2:
  52. print("Waiting on process " + str(process.pid))
  53. returncode = process.wait()
  54. if(returncode == 0):
  55. # Found one
  56. FOUND = FOUND + 1
  57. # Searched all the profiles
  58. if(FOUND > 0):
  59. exit(0)
  60. exit(255)