#! /usr/bin/python
import boto.vpc
import shlex
import json
import time
import sys

args_file = sys.argv[1]
args_data = file(args_file).read()

def dumpErrorInfo(dmsg, berr=True):
  
  print json.dumps(dmsg,
                   sort_keys=True,
                   indent=4,
                   separators=(',', ': ')
                  )

  if berr:
    sys.exit(1)
  else:
    sys.exit(0)
           
def deleteIGW(igwid, region, **kwargs):
  '''
    Routine to delete an Internet Gateway.
  '''
  delay = kwargs.get("delay", 5)
  timeout = kwargs.get("timeout", 300)
  vpcid = kwargs.get("vpc_id", None)

  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      if vpcid and conn.get_all_vpcs(vpcid)[0].state == "available":
        if conn.get_all_internet_gateways(igwid)[0].state == "deleted":
          d["msg"] = "Internet Gateway %s is already deleted" %str(igwid)
          dumpErrorInfo(d, False)

        if conn.get_all_internet_gateways(igwid)[0].attachments[0].state != "detached":
          if not conn.detach_internet_gateway(igwid, vpcid):
            d["msg"] = "Internet Gateway %s detachment from VPC %s failed" %(str(igwid), str(vpcid))
            dumpErrorInfo(d)
          else:
            strttme = time.time()
            while conn.get_all_internet_gateways(igwid)[0].attachments[0].state == "detaching":
              time.sleep(float(delay))
              if int(strttme-time.time()) > timeout:
                d["msg"] = "Internet Gateway %s detach from VPC %s timeout" %(str(igwid), str(vpcid))
                dumpErrorInfo(d)
        try:
          if not conn.delete_internet_gateway(igwid):
              d["msg"] = "Internet Gateway %s deletion failed" %(str(igwid))
              dumpErrorInfo(d)
          else:
            strttme = time.time()
            while conn.get_all_internet_gateways(igwid)[0].state != "deleted":
              time.sleep(float(delay))
              if int(strttme-time.time()) > timeout:
                d["msg"] = "Internet Gateway %s deletion time out" %str(igwid)
                dumpErrorInfo(d)

          d["changed"] = True
          d["msg"] = "Internet Gateway %s deleted" %str(igwid)
          dumpErrorInfo(d, False)
        except Exception, e:
          dumpErrorInfo({
                         "failed" : True,
                         "msg" : "%s" %str(e)
                       })
                         
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })   

def createIGW(region, **kwargs):
  '''
    Routine to create an Internet Gateway.
  '''
  timeout = kwargs.get("timeout", 5)
  vpcid = kwargs.get("vpc_id", None)

  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      try:
        igw = conn.create_internet_gateway()
        time.sleep(float(timeout))
        if conn.get_all_internet_gateways(igw.id)[0].state != 'deleted':
          d["id"] = igw.id
          if vpcid:
            if conn.get_all_vpcs(vpcid)[0].state == "available":
              conn.attach_internet_gateway(igw.id, vpcid)
 
        else:
          d["msg"] = "Seems Internet Gateway creation taking time, please check later" 
        d["changed"] = True
        dumpErrorInfo(d, False)
               
      except Exception, e:
        dumpErrorInfo({
                       "failed" : True,
                       "msg" : "%s" %str(e)
                     })
    else:
      dumpErrorInfo({
                     "failed" : True,
                     "msg" : "Null VPC connection object returned"
                   })
  
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })

def dumpIGW(vpcid, region):
  '''
    Routine to dump an Internet Gateway id.
  '''
  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      try:
        d["id"] = conn.get_all_internet_gateways(filters={"attachment.vpc_id":vpcid})[0].id
        dumpErrorInfo(d, False)
  
      except Exception, e:
        dumpErrorInfo({
                       "failed" : True,
                       "msg" : "%s" %str(e)
                     })
    else:
      dumpErrorInfo({
                     "failed" : True,
                     "msg" : "Null VPC connection object returned"
                   })
  
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })
  
def delCrteIGW():
  '''
    Routine to create or delete an Internet Gateway.
  '''
  if not "region=" in args_data:
    dumpErrorInfo({
                  "failed" : True,
                  "msg" : "region is the required argument"
                 })

  if not "state=" in args_data:
    dumpErrorInfo({
                  "failed" : True,
                  "msg" : "state is the required argument"
                 })
  else:
    if "state=absent" in args_data:
      if not "igw_id=" in args_data:
        dumpErrorInfo({
                      "failed" : True,
                      "msg" : "igw_id is the required argument"
                     })
    elif "state=dump" in args_data:
      if not "vpc_id" in args_data:
        dumpErrorInfo({
                      "failed" : True,
                      "msg" : "vpc_id is the required argument"
                     })

  arguments = shlex.split(args_data)

  d = {} 
  for arg in arguments:
    # ignore any arguments without an equals in it
    if "=" in arg:
        (key, value) = arg.split("=")

        if key == "state":
          d["state"] = value
        elif key == "igw_id":
          d["igw_id"] = value
        elif key == "vpc_id":
          d["vpc_id"] = value
        elif key == "timeout":
          d["timeout"] = value
        elif key == "region":
          d["region"] = value
        
  if d["state"] == "present":
    if d.has_key("vpc_id"):
      createIGW(d["region"], vpc_id=d["vpc_id"])
    else:
      createIGW(d["region"])
    
  elif d["state"] == "absent":
    if d.has_key("vpc_id"):
      deleteIGW(d["igw_id"], d["region"], vpc_id=d["vpc_id"])
    else:
      deleteIGW(d["igw_id"], d["region"])

  elif d["state"] == "dump":
    dumpIGW(d["vpc_id"], d["region"]) 

delCrteIGW()

eea66cc67e4fd19846ac3031e842dcf4fb9ba331
#! /usr/bin/python
import boto.vpc
import shlex
import json
import time
import sys

args_file = sys.argv[1]
args_data = file(args_file).read()

def dumpErrorInfo(dmsg, berr=True):
  
  print json.dumps(dmsg,
                   sort_keys=True,
                   indent=4,
                   separators=(',', ': ')
                  )

  if berr:
    sys.exit(1)
  else:
    sys.exit(0)
           
def deleteIGW(igwid, region, **kwargs):
  '''
    Routine to delete an Internet Gateway.
  '''
  delay = kwargs.get("delay", 5)
  timeout = kwargs.get("timeout", 300)
  vpcid = kwargs.get("vpc_id", None)

  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      if vpcid and conn.get_all_vpcs(vpcid)[0].state == "available":
        if conn.get_all_internet_gateways(igwid)[0].state == "deleted":
          d["msg"] = "Internet Gateway %s is already deleted" %str(igwid)
          dumpErrorInfo(d, False)

        if conn.get_all_internet_gateways(igwid)[0].attachments[0].state != "detached":
          if not conn.detach_internet_gateway(igwid, vpcid):
            d["msg"] = "Internet Gateway %s detachment from VPC %s failed" %(str(igwid), str(vpcid))
            dumpErrorInfo(d)
          else:
            strttme = time.time()
            while conn.get_all_internet_gateways(igwid)[0].attachments[0].state == "detaching":
              time.sleep(float(delay))
              if int(strttme-time.time()) > timeout:
                d["msg"] = "Internet Gateway %s detach from VPC %s timeout" %(str(igwid), str(vpcid))
                dumpErrorInfo(d)
        try:
          if not conn.delete_internet_gateway(igwid):
              d["msg"] = "Internet Gateway %s deletion failed" %(str(igwid))
              dumpErrorInfo(d)
          else:
            strttme = time.time()
            while conn.get_all_internet_gateways(igwid)[0].state != "deleted":
              time.sleep(float(delay))
              if int(strttme-time.time()) > timeout:
                d["msg"] = "Internet Gateway %s deletion time out" %str(igwid)
                dumpErrorInfo(d)

          d["changed"] = True
          d["msg"] = "Internet Gateway %s deleted" %str(igwid)
          dumpErrorInfo(d, False)
        except Exception, e:
          dumpErrorInfo({
                         "failed" : True,
                         "msg" : "%s" %str(e)
                       })
                         
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })   

def createIGW(region, **kwargs):
  '''
    Routine to create an Internet Gateway.
  '''
  timeout = kwargs.get("timeout", 5)
  vpcid = kwargs.get("vpc_id", None)

  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      try:
        igw = conn.create_internet_gateway()
        time.sleep(float(timeout))
        if conn.get_all_internet_gateways(igw.id)[0].state != 'deleted':
          d["id"] = igw.id
          if vpcid:
            if conn.get_all_vpcs(vpcid)[0].state == "available":
              conn.attach_internet_gateway(igw.id, vpcid)
 
        else:
          d["msg"] = "Seems Internet Gateway creation taking time, please check later" 
        d["changed"] = True
        dumpErrorInfo(d, False)
               
      except Exception, e:
        dumpErrorInfo({
                       "failed" : True,
                       "msg" : "%s" %str(e)
                     })
    else:
      dumpErrorInfo({
                     "failed" : True,
                     "msg" : "Null VPC connection object returned"
                   })
  
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })

def dumpIGW(vpcid, region):
  '''
    Routine to dump an Internet Gateway id.
  '''
  try:
    conn = boto.vpc.connect_to_region(region)
    d = { "changed" : False, }
    if conn:
      try:
        d["id"] = conn.get_all_internet_gateways(filters={"attachment.vpc_id":vpcid})[0].id
        dumpErrorInfo(d, False)
  
      except Exception, e:
        dumpErrorInfo({
                       "failed" : True,
                       "msg" : "%s" %str(e)
                     })
    else:
      dumpErrorInfo({
                     "failed" : True,
                     "msg" : "Null VPC connection object returned"
                   })
  
  except Exception, e:
    dumpErrorInfo({
                   "failed" : True,
                   "msg" : "%s" %str(e)
                 })
  
def delCrteIGW():
  '''
    Routine to create or delete an Internet Gateway.
  '''
  if not "region=" in args_data:
    dumpErrorInfo({
                  "failed" : True,
                  "msg" : "region is the required argument"
                 })

  if not "state=" in args_data:
    dumpErrorInfo({
                  "failed" : True,
                  "msg" : "state is the required argument"
                 })
  else:
    if "state=absent" in args_data:
      if not "igw_id=" in args_data:
        dumpErrorInfo({
                      "failed" : True,
                      "msg" : "igw_id is the required argument"
                     })
    elif "state=dump" in args_data:
      if not "vpc_id" in args_data:
        dumpErrorInfo({
                      "failed" : True,
                      "msg" : "vpc_id is the required argument"
                     })

  arguments = shlex.split(args_data)

  d = {} 
  for arg in arguments:
    # ignore any arguments without an equals in it
    if "=" in arg:
        (key, value) = arg.split("=")

        if key == "state":
          d["state"] = value
        elif key == "igw_id":
          d["igw_id"] = value
        elif key == "vpc_id":
          d["vpc_id"] = value
        elif key == "timeout":
          d["timeout"] = value
        elif key == "region":
          d["region"] = value
        
  if d["state"] == "present":
    if d.has_key("vpc_id"):
      createIGW(d["region"], vpc_id=d["vpc_id"])
    else:
      createIGW(d["region"])
    
  elif d["state"] == "absent":
    if d.has_key("vpc_id"):
      deleteIGW(d["igw_id"], d["region"], vpc_id=d["vpc_id"])
    else:
      deleteIGW(d["igw_id"], d["region"])

  elif d["state"] == "dump":
    dumpIGW(d["vpc_id"], d["region"]) 

delCrteIGW()
