class Awsom::Vpc

Public Class Methods

new(name, cidr:) click to toggle source
# File lib/awsom/vpc.rb, line 8
def initialize(name, cidr:)
  @name = name
  @cidr = cidr
end

Public Instance Methods

created() click to toggle source
# File lib/awsom/vpc.rb, line 19
def created
  id = find_id
  if id
    vpc = vpc(id)
    tag(vpc) if not tagged?(vpc)
    id
  else
    create
  end
end
id() click to toggle source
# File lib/awsom/vpc.rb, line 13
def id
  id = find_id
  error "specified vpc #{@name} doesn't exist" if not id
  id
end

Private Instance Methods

create() click to toggle source
# File lib/awsom/vpc.rb, line 32
def create
  resp = Ec2.create_vpc(cidr_block: @cidr)
  logger.info "(#{@name}) created vpc: #{@cidr}"
  id = resp.vpc.vpc_id
  vpc = vpc(id)
  tag(vpc)
  id
rescue Aws::Errors::ServiceError, ArgumentError
  raise Error, "while creating vpc #{@name}"
end
find_id() click to toggle source
# File lib/awsom/vpc.rb, line 67
def find_id
  filters = [
    { name: "cidr", values: [@cidr.to_s] }
  ]
  
  result = Ec2.describe_vpcs(filters: filters)
  num_results = result.vpcs.size
  raise Error, "mulitple vpcs found for name #{@name}" if num_results > 1
  if num_results == 1
    vpc = result.vpcs.first
    verify(vpc)
    result.vpc.first.vpc_id
  else
    false
  end
end
tag(vpc) click to toggle source
# File lib/awsom/vpc.rb, line 47
def tag(vpc)
  return if tagged?(vpc)
  vpc.create_tags(
    tags: [ { key: "Name", value: @name } ]
  )
  vpc.load
end
tagged?(vpc) click to toggle source
# File lib/awsom/vpc.rb, line 55
def tagged?(vpc)
  vpc.tags.any? { |tag| tag.key == "Name"}
end
verify(vpc) click to toggle source
# File lib/awsom/vpc.rb, line 59
def verify(vpc)
  name_tag = vpc.tags.find { |tag| tag.key == "Name" }
  return if not name_tag
  if name_tag.value != @name
    raise Error, "vpc #{@name} already tagged with another name #{name_tag}"
  end
end
vpc(id) click to toggle source
# File lib/awsom/vpc.rb, line 43
def vpc(id)
  Aws::EC2::Vpc.new(id)
end