vpcs.rb 2.5 KB

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