vpcs.rb 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # frozen_string_literal: true
  2. require 'neoinfra'
  3. require 'vpc'
  4. require 'accounts'
  5. require 'fog-aws'
  6. require 'neo4j'
  7. # NeoInfra Account information
  8. module NeoInfra
  9. # Provide informations about the accounts available
  10. class Vpcs
  11. def non_default_vpc_count
  12. p Vpc.all
  13. 21
  14. end
  15. def default_vpc_count
  16. 22
  17. end
  18. def list_vpcs
  19. Vpc.all.collect{|x| {'vpc_id' => x.vpc_id, 'name'=>x.name, 'region' => x.region.region, 'owner' => x.owned.name, 'cidr' => x.cidr, 'default' => x.default} }.select{ |y| y['default'] == "false"}
  20. end
  21. def load
  22. aws = NeoInfra::Aws.new
  23. @cfg = NeoInfra::Config.new
  24. neo4j_url = "http://#{@cfg.neo4j[:host]}:#{@cfg.neo4j[:port]}"
  25. Neo4j::Session.open(:server_db, neo4j_url)
  26. @cfg.accounts.each do |account|
  27. base_conf = {
  28. provider: 'AWS',
  29. aws_access_key_id: account[:key],
  30. aws_secret_access_key: account[:secret]
  31. }
  32. aws.regions.each do |region|
  33. region_conf = { region: region }
  34. new_conn = Fog::Compute.new(region_conf.merge(base_conf))
  35. # Get VPCs
  36. new_conn.vpcs.all.each do |vpc|
  37. next unless Vpc.where(vpc_id: vpc.id).empty?
  38. vpc_name = if vpc.tags.empty?
  39. vpc.id
  40. elsif vpc.tags.key? 'Name'
  41. vpc.tags['Name']
  42. else
  43. vpc.id
  44. end
  45. vpc_id = Vpc.new(
  46. vpc_id: vpc.id,
  47. name: vpc_name,
  48. cidr: vpc.cidr_block,
  49. state: vpc.state,
  50. default: vpc.is_default.to_s
  51. )
  52. vpc_id.save
  53. AccountVpc.create(from_node: vpc_id, to_node: AwsAccount.where(name: account[:name]).first)
  54. VpcRegion.create(from_node: vpc_id, to_node: Region.where(region: region).first)
  55. end
  56. # Get all Subnets
  57. new_conn.subnets.all.each do |subnet|
  58. next unless Subnet.where(subnet_id: subnet.subnet_id).empty?
  59. subnet_name = if subnet.tag_set.empty?
  60. subnet.subnet_id
  61. elsif subnet.tag_set.key? 'Name'
  62. subnet.tag_set['Name']
  63. else
  64. subnet.subnet_id
  65. end
  66. sn = Subnet.new(
  67. subnet_id: subnet.subnet_id,
  68. cidr: subnet.cidr_block,
  69. name: subnet_name,
  70. ip_count: subnet.available_ip_address_count,
  71. state: subnet.state
  72. )
  73. sn.save
  74. VpcSubnet.create(from_node: sn, to_node: Vpc.where(vpc_id: subnet.vpc_id).first)
  75. begin
  76. SubnetAz.create(from_node: sn, to_node: Az.where(az: subnet.availability_zone).first)
  77. rescue
  78. # Handle the case of hanging subnets
  79. puts "Account #{account[:name]} couldn't load the following subnet:"
  80. p subnet
  81. end
  82. end
  83. end
  84. end
  85. end
  86. end
  87. end