aws_helper.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. require 'fileutils'
  2. module OpenShift
  3. module Ops
  4. class AwsHelper
  5. MYDIR = File.expand_path(File.dirname(__FILE__))
  6. def self.get_list()
  7. cmd = "#{MYDIR}/../inventory/aws/ec2.py --list"
  8. hosts = %x[#{cmd} 2>&1]
  9. raise "Error: failed to list hosts\n#{hosts}" unless $?.exitstatus == 0
  10. return JSON.parse(hosts)
  11. end
  12. def self.get_hosts()
  13. hosts = get_list()
  14. retval = []
  15. hosts['_meta']['hostvars'].each do |host, info|
  16. retval << OpenStruct.new({
  17. :name => info['ec2_tag_Name'],
  18. :env => info['ec2_tag_environment'] || 'UNSET',
  19. :external_ip => info['ec2_ip_address'],
  20. :public_dns => info['ec2_public_dns_name']
  21. })
  22. end
  23. retval.sort_by! { |h| [h.env, h.name] }
  24. return retval
  25. end
  26. def self.get_host_details(host)
  27. hosts = get_list()
  28. dns_names = hosts["tag_Name_#{host}"]
  29. raise "Error: host not found [#{host}]" if dns_names.nil?
  30. return hosts['_meta']['hostvars'][dns_names.first]
  31. end
  32. def self.check_creds()
  33. raise "AWS_ACCESS_KEY_ID environment variable must be set" if ENV['AWS_ACCESS_KEY_ID'].nil?
  34. raise "AWS_SECRET_ACCESS_KEY environment variable must be set" if ENV['AWS_SECRET_ACCESS_KEY'].nil?
  35. end
  36. def self.clear_inventory_cache()
  37. path = "#{ENV['HOME']}/.ansible/tmp"
  38. cache_files = ["#{path}/ansible-ec2.cache", "#{path}/ansible-ec2.index"]
  39. FileUtils.rm(cache_files)
  40. end
  41. def self.generate_env_tag(env)
  42. return { "environment" => env }
  43. end
  44. def self.generate_env_tag_name(env)
  45. h = generate_env_tag(env)
  46. return "tag_#{h.keys.first}_#{h.values.first}"
  47. end
  48. def self.generate_host_type_tag(host_type)
  49. return { "host-type" => host_type }
  50. end
  51. def self.generate_host_type_tag_name(host_type)
  52. h = generate_host_type_tag(host_type)
  53. return "tag_#{h.keys.first}_#{h.values.first}"
  54. end
  55. def self.generate_env_host_type_tag(env, host_type)
  56. return { "env-host-type" => "#{env}-#{host_type}" }
  57. end
  58. def self.generate_env_host_type_tag_name(env, host_type)
  59. h = generate_env_host_type_tag(env, host_type)
  60. return "tag_#{h.keys.first}_#{h.values.first}"
  61. end
  62. end
  63. end
  64. end