本文整理汇总了Python中boto.vpc.VPCConnection.get_all_vpcs方法的典型用法代码示例。如果您正苦于以下问题:Python VPCConnection.get_all_vpcs方法的具体用法?Python VPCConnection.get_all_vpcs怎么用?Python VPCConnection.get_all_vpcs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类boto.vpc.VPCConnection
的用法示例。
在下文中一共展示了VPCConnection.get_all_vpcs方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def run(self, terms, variables=None, **kwargs):
ret = []
# Below i will implement
valid_lookups = {
'id' : None
'dhcp_options_id' : None
'state' : None
'cidr_block' : None
'is_default' : None
'instance_tenancy' : None
'classic_link_enabled' : None
}
conn = VPCConnection()
for term in terms:
params = term.split(' ')
key_to_lookup = params[0]
try:
assert( key_to_lookup in valid_lookups )
except (AssertionError) as e:
raise AnsibleError(e)
vpc_filter = {}
for param in params[1:]:
tag, value = param.split('=')
vpc_filter.update({'tag:'+ tag : value})
vpcs = conn.get_all_vpcs(None, vpc_filter)
if len(vpcs) > 1:
ret = [ x.get( key_to_lookup ) for x in vpcs ]
return ret
示例2: fetch_environment
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def fetch_environment(cls, vpc_id=None, environment_name=None):
"""
Returns an instance of this class for the specified VPC, or None if it does not exist
"""
vpc_conn = VPCConnection()
if vpc_id:
vpc = vpc_conn.get_all_vpcs(vpc_ids=[vpc_id])
elif environment_name:
vpc = vpc_conn.get_all_vpcs(filters={"tag:Name": environment_name})
else:
raise VPCEnvironmentError("Expect vpc_id or environment_name")
if vpc:
vpc = vpc[0]
return cls(vpc.tags["Name"], vpc.tags["type"], vpc)
else:
return None
示例3: find_vpc_id_by_name
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def find_vpc_id_by_name(vpc_name):
"""Find VPC by name"""
vpc_conn = VPCConnection()
vpc_ids = vpc_conn.get_all_vpcs(filters={'tag:Name': vpc_name})
if len(vpc_ids) == 1:
return vpc_ids[0].id
elif len(vpc_ids) == 0:
raise VPCNameNotFound("No VPC is named as {}".format(vpc_name))
else:
raise MultipleVPCsForVPCNameError("More than 1 VPC is named as {}".format(vpc_name))
示例4: discover_vpc
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def discover_vpc(self,vpc_id):
try:
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY=self.find_aws_creds()
except:
logger.info("Error: {0}: Cannot retrieve boto credentials".format(__name__))
try:
conn_vpc = VPCConnection(aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
a = conn_vpc.get_all_vpcs()
for b in a:
if b.tags['Name'].lower() == vpc_id:
vpc_id=b.id
else:
vpc_id=''
except:
logger.info("Error: {0}: conn_vpc cannot VPCConnection()".format(__name__))
return vpc_id
示例5: _get_vpc_details
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def _get_vpc_details(self):
"""
Create dictonary with VPC's info and tags
"""
# Connect to AWS for VPC
vpc_conn = VPCConnection()
# Grab VPCs
vpcs_data = vpc_conn.get_all_vpcs()
for vpc in vpcs_data:
tags = {}
tags['state'] = vpc.state
tags['cidr'] = vpc.cidr_block
for key, value in vpc.tags.items():
tags[key.lower()] = value.lower()
# assing vpcs to class vpcs
self.vpcs = {vpc.id: tags}
示例6: get_vpc_id
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def get_vpc_id(self, env):
"""
Return VPC ID from Stack Name
"""
# VPC connection
self.api_call()
region = boto.ec2.get_region("us-west-2")
vpc_conn = VPCConnection(region=region)
# get dict of VPC
vpc_dict = {}
for vpc in vpc_conn.get_all_vpcs():
vpc_dict[vpc.tags.get("Env")] = vpc.id
# search Env in VPC tag name
if env not in vpc_dict:
print "VPC name not found."
sys.exit(1)
else:
return vpc_dict[env]
示例7: getOtherResourceApartFromEC2Instances
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def getOtherResourceApartFromEC2Instances(self):
#all excpetion will be ignored since other data is only for info sake
try :
self.netIntf = self.conn.get_all_network_interfaces()
except:
pass
try :
self.eipList = self.conn.get_all_addresses()
except:
pass
try :
self.keypair = self.conn.get_all_key_pairs()
except :
pass
try :
self.sgList = self.conn.get_all_security_groups()
except:
pass
try :
self.volList = self.conn.get_all_volumes()
except :
pass
for key in self.insts.keys():
if len(self.insts[key]) > 0 :
for inst in self.insts[key]:
img_present = False
for img in self.amiList:
if img.id == inst.image_id:
img_present = True
break
if img_present == False :
self.amiList.append(self.conn.get_image(inst.botoInstInfo.image_id))
try :
vpcConn =VPCConnection(aws_access_key_id=self.conf.access_key_id,aws_secret_access_key=self.conf.access_key_sec,debug=10)
self.vpcList=vpcConn.get_all_vpcs()
except:
pass
示例8: zones_rm
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
region.name,
aws_access_key_id=accesskey,
aws_secret_access_key=secretkey,
validate_certs=False
)
# Zones
maps['zones'].append(
zones_rm(
region_id, ec2regionconn.get_all_zones())
)
# VPCs
maps['VPCs'].append(
vpcs_rm(
region_id, vpcregionconn.get_all_vpcs())
)
# VPNGateways
maps['VPNGateways'].append(
vpn_gateways_rm(
region_id, vpcregionconn.get_all_vpn_gateways()
)
)
if sqsconnection:
maps['queues'].append(vpn_queues_rm(
region_id, sqsconnection.get_all_queues()
))
else:
log.error(
示例9: VPCConnection
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
#conn = boto.ec2.connect_to_region(aws_access_key_id=configObj['keys'][0]['aws_access_key'],
# aws_secret_access_key=configObj['keys'][0]['aws_secret_key'])
#print conn
regions = boto.ec2.regions(aws_access_key_id=configObj['keys'][0]['aws_access_key'],
aws_secret_access_key=configObj['keys'][0]['aws_secret_key'])
print regions
conn = VPCConnection(aws_access_key_id=configObj['keys'][0]['aws_access_key'],
aws_secret_access_key=configObj['keys'][0]['aws_secret_key'],
region=regions[1],
proxy='bne-app-proxy.au.fcl.internal',
proxy_port=3128
)
filter = [('state','available')]
vpc_status_list = conn.get_all_vpcs(None, filter)
#print type(vpc_status_list)
for vpc in vpc_status_list:
for tag,value in vpc.tags.items():
print tag+ " value: "+value
subnet_filter = [('vpcId',vpc.id)]
vpc_subnets_list = conn.get_all_subnets(None, subnet_filter)
print vpc_subnets_list
示例10: node_install
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def node_install(cn=def_cn,inst_type_idx=def_inst_type,idn=0,
avz=def_default_avz,rt=def_default_requesttype,
group_name='oggmssh',
ssh_port=22,
cidr='0.0.0.0/0'):
"""
Request and prepare single instance
"""
# FSO---connect
cloud = boto.ec2.connect_to_region(avz[:-1],profile_name=ec2Profile)
aminfo = cloud.get_image(def_ami[avz[:-1]])
vpcconn = VPCConnection(region=cloud.region)
try:
vpc_id, subnet_id = def_subnet[avz]
vpc = vpcconn.get_all_vpcs(vpc_ids=[vpc_id])[0]
except:
vpc_id = None
subnet_id = None
vpc = None
# FSO---check if node with same name already exists
if node_exists(cn + '_node' + str(idn)):
print("Node already exists")
sys.exit()
# Check if ssh keypair exists
key_name = get_keypair_name(avz[:-1])
check_keypair(cloud, key_name)
# FSO---create a bigger root device
dev_sda1 = EBSBlockDeviceType()
dev_sda1.size = rootfs_size_gb
dev_sda1.delete_on_termination = True
bdm = BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
dev_sdf_vol = get_user_persist_ebs(cloud, avz)
# Check to see if specified security group already exists.
# If we get an InvalidGroup.NotFound error back from EC2,
# it means that it doesn't exist and we need to create it.
try:
group = cloud.get_all_security_groups(groupnames=[group_name])[0]
except cloud.ResponseError as e:
if e.code == 'InvalidGroup.NotFound':
print('Creating Security Group: %s' % group_name)
# Create a security group to control access to instance via SSH.
group = cloud.create_security_group(group_name, 'A group that allows SSH access')
else:
raise
if vpc is not None:
try:
group.authorize('tcp', 0, 65535, vpc.cidr_block)
except cloud.ResponseError as e:
if e.code != 'InvalidPermission.Duplicate':
raise
try:
group.authorize('udp', 0, 65535, vpc.cidr_block)
except cloud.ResponseError as e:
if e.code != 'InvalidPermission.Duplicate':
raise
try:
group.authorize('icmp', 0, 255, vpc.cidr_block)
except cloud.ResponseError as e:
if e.code != 'InvalidPermission.Duplicate':
raise
# Add a rule to the security group to authorize SSH traffic
# on the specified port.
try:
group.authorize('tcp', ssh_port, ssh_port, cidr)
except cloud.ResponseError as e:
if e.code == 'InvalidPermission.Duplicate':
print('Security Group: %s already authorized' % group_name)
else:
raise
log_with_ts("request node "+str(idn))
print('Reserving instance for node', aminfo.id, instance_infos[inst_type_idx]['type'], aminfo.name, aminfo.region)
if rt == 'spot':
print("placing node in ",avz)
requests = cloud.request_spot_instances(def_price,
def_ami[avz[:-1]],
count=1,
type='one-time',
security_group_ids=[group.id],
key_name=key_name,
placement=avz,
subnet_id=subnet_id,
instance_type=instance_infos[inst_type_idx]['type'],
block_device_map=bdm)
req_ids = [request.id for request in requests]
instance_ids = wait_for_fulfillment(cloud,req_ids)
instances = cloud.get_only_instances(instance_ids=instance_ids)
node = instances[0]
log_with_ts("fullfilled spot node "+str(idn))
else:
#.........这里部分代码省略.........
示例11: raw_input
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
"""
# ********** User interactive **********
print "Type CIDR block to use between /16 and /28. E.G. 10.0.0.0/24,
Press 'Enter' when finished"
VPC_CIDR = raw_input()
print "Type the Name for VPC (to use as Tag), Press 'Enter' when finished"
VPC_NAME = raw_input()
"""
# boto.set_stream_logger("Stratus")
print "Boto Version: ", boto.Version, "\n"
# print boto.rds2.regions()
exist_vpc = vpcc.get_all_vpcs(filters=[("cidrBlock", VPC_CIDR)])
if not len(exist_vpc):
new_vpc = vpcc.create_vpc(cidr_block=VPC_CIDR, instance_tenancy=VPC_TENANCY, dry_run=BOOLEAN_DRYRUN)
aws_vpc_id = new_vpc.id
print "No existing VPC"
print "New VPC created: ", aws_vpc_id, "\n"
else:
# Return 1st object from list
aws_vpc_id = str(exist_vpc.pop(0))[4:]
print "Identical CIDR already used. Skipped creation."
print "Existing VPC ID: {}\n".format(aws_vpc_id)
# Use existing VPC
new_vpc = vpcc.get_all_vpcs(filters=[("cidrBlock", VPC_CIDR)])
"""
# Doesn't work due to VPC dependency
示例12: list_vpcs
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def list_vpcs():
"""Returns list of boto.vpc.vpc.VPC classes, one for each existing VPC"""
vpc_conn = VPCConnection()
return vpc_conn.get_all_vpcs()
示例13: process
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def process(self, device, results, log):
log.info(
'Modeler %s processing data for device %s',
self.name(), device.id)
accesskey = getattr(device, 'ec2accesskey', None)
secretkey = getattr(device, 'ec2secretkey', None)
old_logger = boto.log.error
boto.log.error = lambda x: x
try:
if not secretkey or not accesskey:
raise EC2ResponseError('', '', '')
ec2conn = EC2Connection(accesskey, secretkey)
s3connection = S3Connection(accesskey, secretkey)
ec2_regions = ec2conn.get_all_regions()
except EC2ResponseError:
log.error('Invalid Keys. '
'Check your EC2 Access Key and EC2 Secret Key.')
return
finally:
boto.log.error = old_logger
maps = collections.OrderedDict([
('regions', []),
('s3buckets', []),
('instance types', []),
('zones', []),
('VPCs', []),
('VPC subnets', []),
('VPNGateways', []),
('images', []),
('instances', []),
('volumes', []),
('snapshots', []),
('queues', []),
('elastic_ips', []),
('reservations', []),
('account', []),
('reserved_instances', []),
])
image_filters = []
region_oms = []
for region in ec2_regions:
region_id = prepId(region.name)
region_oms.append(ObjectMap(data={
'id': region_id,
'title': region.name,
}))
ec2regionconn = EC2Connection(accesskey, secretkey, region=region)
vpcregionconn = VPCConnection(accesskey, secretkey, region=region)
sqsconnection = boto.sqs.connect_to_region(
region.name,
aws_access_key_id=accesskey,
aws_secret_access_key=secretkey
)
# Zones
maps['zones'].append(
zones_rm(
region_id, ec2regionconn.get_all_zones())
)
# VPCs
maps['VPCs'].append(
vpcs_rm(
region_id, vpcregionconn.get_all_vpcs())
)
# VPNGateways
maps['VPNGateways'].append(
vpn_gateways_rm(
region_id, vpcregionconn.get_all_vpn_gateways()
)
)
maps['queues'].append(vpn_queues_rm(
region_id, sqsconnection.get_all_queues()
))
maps['VPC subnets'].append(vpc_subnets_rm(
region_id, vpcregionconn.get_all_subnets()
))
# Instances
maps['instances'].append(instances_rm(
region_id,
device,
ec2regionconn.get_only_instances(filters=INSTANCE_FILTERS),
image_filters
))
# Images
if image_filters:
maps['images'].append(
images_rm(region_id, ec2regionconn.get_all_images(
image_ids=image_filters))
#.........这里部分代码省略.........
示例14: process
# 需要导入模块: from boto.vpc import VPCConnection [as 别名]
# 或者: from boto.vpc.VPCConnection import get_all_vpcs [as 别名]
def process(self, device, results, log):
log.info(
'Modeler %s processing data for device %s',
self.name(), device.id)
accesskey = getattr(device, 'ec2accesskey', None)
if not accesskey:
log.error('%s: EC2 access key not set. Not discovering.')
return
secretkey = getattr(device, 'ec2secretkey', None)
if not secretkey:
log.error('%s: EC2 secret key not set. Not discovering.')
return
maps = collections.OrderedDict([
('regions', []),
('instance types', []),
('zones', []),
('VPCs', []),
('VPC subnets', []),
('instances', []),
('volumes', []),
('account', []),
])
instance_filters = {
'instance-state-name': [
'pending',
'running',
'shutting-down',
'stopping',
'stopped',
],
}
ec2conn = EC2Connection(accesskey, secretkey)
region_oms = []
for region in ec2conn.get_all_regions():
region_id = prepId(region.name)
region_oms.append(ObjectMap(data={
'id': region_id,
'title': region.name,
}))
ec2regionconn = EC2Connection(accesskey, secretkey, region=region)
vpcregionconn = VPCConnection(accesskey, secretkey, region=region)
# Zones
maps['zones'].append(
zones_rm(
region_id,
ec2regionconn.get_all_zones()))
# VPCs
maps['VPCs'].append(
vpcs_rm(
region_id,
vpcregionconn.get_all_vpcs()))
# VPC Subnets
maps['VPC subnets'].append(
vpc_subnets_rm(
region_id,
vpcregionconn.get_all_subnets()))
# Instances
maps['instances'].append(
instances_rm(
region_id,
ec2regionconn.get_all_instances(
filters=instance_filters)))
# Volumes
maps['volumes'].append(
volumes_rm(
region_id,
ec2regionconn.get_all_volumes()))
# Regions
maps['regions'].append(RelationshipMap(
relname='regions',
modname=MODULE_NAME['EC2Region'],
objmaps=region_oms))
# Trigger discovery of instance guest devices.
maps['account'].append(ObjectMap(data={
'setDiscoverGuests': True,
}))
return list(chain.from_iterable(maps.itervalues()))