本文整理汇总了Python中dopy.manager.DoManager类的典型用法代码示例。如果您正苦于以下问题:Python DoManager类的具体用法?Python DoManager怎么用?Python DoManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DoManager类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_droplets_from_digital_ocean
def load_droplets_from_digital_ocean(self):
''' Use dopy to get droplet information from DigitalOcean and save data in cache files '''
manager = DoManager(None, self.access_token, api_version=2)
self.data['droplets'] = manager.all_active_droplets()
self.index['host_to_droplet'] = self.build_index(self.data['droplets'], 'ip_address', 'id', False)
self.build_inventory()
self.write_to_cache()
示例2: load_droplets_from_digital_ocean
def load_droplets_from_digital_ocean(self):
''' Use dopy to get droplet information from DigitalOcean and save data in cache files '''
manager = DoManager(self.client_id, self.api_key)
self.data['droplets'] = self.sanitize_list(manager.all_active_droplets())
self.index['host_to_droplet'] = self.build_index(self.data['droplets'], 'ip_address', 'id', False)
self.build_inventory()
self.write_to_cache()
示例3: load_droplet_variables_for_host
def load_droplet_variables_for_host(self):
'''Generate a JSON response to a --host call'''
host = self.to_safe(str(self.args.host))
if not host in self.index['host_to_droplet']:
# try updating cache
if not self.args.force_cache:
self.load_all_data_from_digital_ocean()
if not host in self.index['host_to_droplet']:
# host might not exist anymore
return {}
droplet = None
if self.cache_refreshed:
for drop in self.data['droplets']:
if drop['ip_address'] == host:
droplet = self.sanitize_dict(drop)
break
else:
# Cache wasn't refreshed this run, so hit DigitalOcean API
manager = DoManager(None, self.api_token, api_version=2)
droplet_id = self.index['host_to_droplet'][host]
droplet = self.sanitize_dict(manager.show_droplet(droplet_id))
if not droplet:
return {}
# Put all the information in a 'do_' namespace
info = {}
for k, v in droplet.items():
info['do_'+k] = v
return info
示例4: load_all_data_from_digital_ocean
def load_all_data_from_digital_ocean(self):
''' Use dopy to get all the information from DigitalOcean '''
manager = DoManager(self.client_id, self.api_key)
self.data = {}
self.data['regions'] = self.sanitize_list(manager.all_regions())
self.data['images'] = self.sanitize_list(manager.all_images(filter=None))
self.data['sizes'] = self.sanitize_list(manager.sizes())
示例5: __init__
def __init__(self, settings_file='digital_ocean.ini'):
super(DigitalOceanBase, self).__init__()
self.config = Settings(prefix='DO', section='digital_ocean',
filename=settings_file)
self.data_params = {}
self.do = DoManager(self.config.get('client_id'),
self.config.get('api_key'))
示例6: DigitalOceanBase
class DigitalOceanBase(Inventory):
address_field = 'ip_address'
def __init__(self, settings_file='digital_ocean.ini'):
super(DigitalOceanBase, self).__init__()
self.config = Settings(prefix='DO', section='digital_ocean',
filename=settings_file)
self.data_params = {}
self.do = DoManager(self.config.get('client_id'),
self.config.get('api_key'))
@file_cache('/tmp/ansible-droplets-cache.json')
def get_data(self):
if not self.data:
self.data = self.do.all_active_droplets()
return self.data
@file_cache('/tmp/ansible-data-params-cache.json', timeout=3600)
def get_data_params(self):
if not self.data_params:
def _convert(data):
ret = {}
for datum in data:
# Ensure keys are always strings because JSON
# strings are always strings
ret[str(datum['id'])] = datum
return ret
self.data_params['regions'] = _convert(self.do.all_regions())
self.data_params['images'] = _convert(self.do.all_images())
self.data_params['ssh_keys'] = _convert(self.do.all_ssh_keys())
self.data_params['sizes'] = _convert(self.do.sizes())
return self.data_params
def get_data_param(self, host, part, find_key, display_template):
try:
datum = self.get_data_params()[part][str(host[find_key])]
except KeyError:
pass
else:
return (display_template.format(**datum), self.get_address(host))
示例7: load_droplet_variables_for_host
def load_droplet_variables_for_host(self):
'''Generate a JSON response to a --host call'''
host = self.to_safe(str(self.args.host))
if not host in self.index['host_to_droplet']:
# try updating cache
if not self.args.force_cache:
self.load_all_data_from_digital_ocean()
if not host in self.index['host_to_droplet']:
# host might not exist anymore
return {}
droplet = None
if self.cache_refreshed:
for drop in self.data['droplets']:
if drop['ip_address'] == host:
droplet = self.sanitize_dict(drop)
break
else:
# Cache wasn't refreshed this run, so hit DigitalOcean API
manager = DoManager(self.client_id, self.api_key)
droplet_id = self.index['host_to_droplet'][host]
droplet = self.sanitize_dict(manager.show_droplet(droplet_id))
if not droplet:
return {}
# Put all the information in a 'do_' namespace
info = {}
for k, v in droplet.items():
info['do_'+k] = v
# Generate user-friendly variables (i.e. not the ID's)
if droplet.has_key('region_id'):
info['do_region'] = self.index['region_to_name'].get(droplet['region_id'])
if droplet.has_key('size_id'):
info['do_size'] = self.index['size_to_name'].get(droplet['size_id'])
if droplet.has_key('image_id'):
info['do_image'] = self.index['image_to_name'].get(droplet['image_id'])
info['do_distro'] = self.index['image_to_distro'].get(droplet['image_id'])
return info
示例8: load_all_data_from_digital_ocean
def load_all_data_from_digital_ocean(self):
''' Use dopy to get all the information from DigitalOcean and save data in cache files '''
manager = DoManager(None, self.access_token, api_version=2)
self.data = {}
self.data['droplets'] = manager.all_active_droplets()
self.data['regions'] = manager.all_regions()
self.data['images'] = manager.all_images(filter=None)
self.data['sizes'] = manager.sizes()
self.data['ssh_keys'] = manager.all_ssh_keys()
self.data['domains'] = manager.all_domains()
self.index = {}
self.index['region_to_name'] = self.build_index(self.data['regions'], 'name', 'slug')
self.index['size_to_name'] = self.build_index(self.data['sizes'], 'memory', 'slug')
self.index['image_to_name'] = self.build_index(self.data['images'], 'id', 'name')
self.index['image_to_distro'] = self.build_index(self.data['images'], 'id', 'distribution')
self.index['host_to_droplet'] = self.build_index(self.data['droplets'], 'ip_address', 'id', False)
self.build_inventory()
self.write_to_cache()
示例9: get_config
# MAX_AGE in seconds of a VM
MAX_AGE = get_config(config, 'do_clean', 'max_age', None, 10800, integer=True)
# CHECK_FREQ in seconds of the DO VM status
CHECK_FREQ = get_config(config, 'do_clean', 'check_freq', None, 300, integer=True)
# DONT touch those Droplets (use droplet ids). ex.
# DONT = [ 123456, 654321 ]
RAW_DONT = get_config(config, 'do_clean', 'dont', None, '')
try:
DONT = [ int(val.strip()) for val in RAW_DONT.split(',') if val]
except Exception as e:
print "Invalid format for DONT - %s" % e
sys.exit(1)
if __name__ == '__main__':
do = DoManager(client_id, api_key, api_version=api_version)
while True:
try:
droplets = do.all_active_droplets()
for droplet in droplets:
if droplet.get('id') in DONT:
# Don't kill meeeeee
print 'Not killing %s (%s) - part of the DONT' % (droplet.get('name'), droplet.get('id'))
continue
created = datetime.strptime(droplet.get('created_at'), "%Y-%m-%dT%H:%M:%SZ")
now = datetime.now()
diff = now - created
if diff.seconds > MAX_AGE:
print 'gonna destroy droplet - %s (%s: %s)' % (droplet.get('name'), droplet.get('id'), droplet.get('ip_address'))
do.destroy_droplet(droplet.get('id'))
print 'destroyed droplet - %s (%s: %s)' % (droplet.get('name'), droplet.get('id'), droplet.get('ip_address'))
示例10: __init__
def __init__(self):
''' Main execution path '''
# DigitalOceanInventory data
self.data = {} # All DigitalOcean data
self.inventory = {} # Ansible Inventory
# Define defaults
self.cache_path = '.'
self.cache_max_age = 0
self.use_private_network = False
self.group_variables = {}
# Read settings, environment variables, and CLI arguments
self.read_settings()
self.read_environment()
self.read_cli_args()
# Verify credentials were set
if not hasattr(self, 'api_token'):
print('''Could not find values for DigitalOcean api_token.
They must be specified via either ini file, command line argument (--api-token),
or environment variables (DO_API_TOKEN)''')
sys.exit(-1)
# env command, show DigitalOcean credentials
if self.args.env:
print("DO_API_TOKEN=%s" % self.api_token)
sys.exit(0)
# Manage cache
self.cache_filename = self.cache_path + "/ansible-digital_ocean.cache"
self.cache_refreshed = False
if self.is_cache_valid:
self.load_from_cache()
if len(self.data) == 0:
if self.args.force_cache:
print('''Cache is empty and --force-cache was specified''')
sys.exit(-1)
self.manager = DoManager(None, self.api_token, api_version=2)
# Pick the json_data to print based on the CLI command
if self.args.droplets:
self.load_from_digital_ocean('droplets')
json_data = {'droplets': self.data['droplets']}
elif self.args.regions:
self.load_from_digital_ocean('regions')
json_data = {'regions': self.data['regions']}
elif self.args.images:
self.load_from_digital_ocean('images')
json_data = {'images': self.data['images']}
elif self.args.sizes:
self.load_from_digital_ocean('sizes')
json_data = {'sizes': self.data['sizes']}
elif self.args.ssh_keys:
self.load_from_digital_ocean('ssh_keys')
json_data = {'ssh_keys': self.data['ssh_keys']}
elif self.args.domains:
self.load_from_digital_ocean('domains')
json_data = {'domains': self.data['domains']}
elif self.args.all:
self.load_from_digital_ocean()
json_data = self.data
elif self.args.host:
json_data = self.load_droplet_variables_for_host()
else: # '--list' this is last to make it default
self.load_from_digital_ocean('droplets')
self.build_inventory()
json_data = self.inventory
if self.cache_refreshed:
self.write_to_cache()
if self.args.pretty:
print(json.dumps(json_data, sort_keys=True, indent=2))
else:
print(json.dumps(json_data))
示例11: DigitalOceanInventory
class DigitalOceanInventory(object):
###########################################################################
# Main execution path
###########################################################################
def __init__(self):
''' Main execution path '''
# DigitalOceanInventory data
self.data = {} # All DigitalOcean data
self.inventory = {} # Ansible Inventory
# Define defaults
self.cache_path = '.'
self.cache_max_age = 0
self.use_private_network = False
self.group_variables = {}
# Read settings, environment variables, and CLI arguments
self.read_settings()
self.read_environment()
self.read_cli_args()
# Verify credentials were set
if not hasattr(self, 'api_token'):
print('''Could not find values for DigitalOcean api_token.
They must be specified via either ini file, command line argument (--api-token),
or environment variables (DO_API_TOKEN)''')
sys.exit(-1)
# env command, show DigitalOcean credentials
if self.args.env:
print("DO_API_TOKEN=%s" % self.api_token)
sys.exit(0)
# Manage cache
self.cache_filename = self.cache_path + "/ansible-digital_ocean.cache"
self.cache_refreshed = False
if self.is_cache_valid:
self.load_from_cache()
if len(self.data) == 0:
if self.args.force_cache:
print('''Cache is empty and --force-cache was specified''')
sys.exit(-1)
self.manager = DoManager(None, self.api_token, api_version=2)
# Pick the json_data to print based on the CLI command
if self.args.droplets:
self.load_from_digital_ocean('droplets')
json_data = {'droplets': self.data['droplets']}
elif self.args.regions:
self.load_from_digital_ocean('regions')
json_data = {'regions': self.data['regions']}
elif self.args.images:
self.load_from_digital_ocean('images')
json_data = {'images': self.data['images']}
elif self.args.sizes:
self.load_from_digital_ocean('sizes')
json_data = {'sizes': self.data['sizes']}
elif self.args.ssh_keys:
self.load_from_digital_ocean('ssh_keys')
json_data = {'ssh_keys': self.data['ssh_keys']}
elif self.args.domains:
self.load_from_digital_ocean('domains')
json_data = {'domains': self.data['domains']}
elif self.args.all:
self.load_from_digital_ocean()
json_data = self.data
elif self.args.host:
json_data = self.load_droplet_variables_for_host()
else: # '--list' this is last to make it default
self.load_from_digital_ocean('droplets')
self.build_inventory()
json_data = self.inventory
if self.cache_refreshed:
self.write_to_cache()
if self.args.pretty:
print(json.dumps(json_data, sort_keys=True, indent=2))
else:
print(json.dumps(json_data))
# That's all she wrote...
###########################################################################
# Script configuration
###########################################################################
def read_settings(self):
''' Reads the settings from the digital_ocean.ini file '''
config = ConfigParser.SafeConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + '/digital_ocean.ini')
# Credentials
if config.has_option('digital_ocean', 'api_token'):
self.api_token = config.get('digital_ocean', 'api_token')
#.........这里部分代码省略.........
示例12: DoManager
from dopy.manager import DoManager
import os
API_VERSION = 2
SIZE = '512mb'
REGION = 'nyc2'
PURPOSE = 'wordpress'
VERSION = '1'
IMAGE = 'ubuntu-14-04-x64'
USER_DATA = '''#cloud-config
users:
- name: ansible
ssh-authorized-keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDOd/iTQUd6Hb/KTpDjjPJotOWHfTH71U5L7x9Y4y9bo7Zvtp/m1WZyR55Ut6uBfGHscD5WRNv6VFsRIHRRjiHP+pGkB4piSUNuOduEOL/FCzmytQLmg7mYZZRGHLYXIoFJV/kdXmjexXSySxJSSp5X5EcH/pLWcKhRK9HiX4IGOBZfNwxaL/VODxU989jNXuKPnF6XfuNVf9p7JYkc4zaDy4752pPCWU2oTfq6y5Ll0vqoSpb62gCUf94CYU5eQddIeZEutTi2UiuqbsA7sEvsZpp/iXXvkaCAWMNRY6VMy5AUavDpNk4tZ/ITcieCWYdfDPCBDcfXwgANlVorHGaR [email protected]
sudo: ['ALL=(ALL) NOPASSWD:ALL']
groups: sudo
shell: /bin/bash
runcmd:
- sed -i -e '/^PermitRootLogin/s/^.*$/PermitRootLogin no/' /etc/ssh/sshd_config
- sed -i -e '$aAllowUsers ansible' /etc/ssh/sshd_config
- restart ssh
'''
do = DoManager(None, os.environ['DO_API_TOKEN'], API_VERSION)
results = do.new_droplet('{0}-{1}-{2}'.format(REGION, PURPOSE, VERSION), SIZE, IMAGE, REGION, user_data=USER_DATA)
for i in results.keys():
print('{0}: {1}'.format(i, results[i]))
示例13: DigitalOceanInventory
class DigitalOceanInventory(object):
###########################################################################
# Main execution path
###########################################################################
def __init__(self):
""" Main execution path """
# DigitalOceanInventory data
self.data = {} # All DigitalOcean data
self.inventory = {} # Ansible Inventory
# Define defaults
self.cache_path = "."
self.cache_max_age = 0
# Read settings, environment variables, and CLI arguments
self.read_settings()
self.read_environment()
self.read_cli_args()
# Verify credentials were set
if not hasattr(self, "api_token"):
print """Could not find values for DigitalOcean api_token.
They must be specified via either ini file, command line argument (--api-token),
or environment variables (DO_API_TOKEN)"""
sys.exit(-1)
# env command, show DigitalOcean credentials
if self.args.env:
print "DO_API_TOKEN=%s" % self.api_token
sys.exit(0)
# Manage cache
self.cache_filename = self.cache_path + "/ansible-digital_ocean.cache"
self.cache_refreshed = False
if self.is_cache_valid:
self.load_from_cache()
if len(self.data) == 0:
if self.args.force_cache:
print """Cache is empty and --force-cache was specified"""
sys.exit(-1)
self.manager = DoManager(None, self.api_token, api_version=2)
# Pick the json_data to print based on the CLI command
if self.args.droplets:
self.load_from_digital_ocean("droplets")
json_data = {"droplets": self.data["droplets"]}
elif self.args.regions:
self.load_from_digital_ocean("regions")
json_data = {"regions": self.data["regions"]}
elif self.args.images:
self.load_from_digital_ocean("images")
json_data = {"images": self.data["images"]}
elif self.args.sizes:
self.load_from_digital_ocean("sizes")
json_data = {"sizes": self.data["sizes"]}
elif self.args.ssh_keys:
self.load_from_digital_ocean("ssh_keys")
json_data = {"ssh_keys": self.data["ssh_keys"]}
elif self.args.domains:
self.load_from_digital_ocean("domains")
json_data = {"domains": self.data["domains"]}
elif self.args.all:
self.load_from_digital_ocean()
json_data = self.data
elif self.args.host:
json_data = self.load_droplet_variables_for_host()
else: # '--list' this is last to make it default
self.load_from_digital_ocean("droplets")
self.build_inventory()
json_data = self.inventory
if self.cache_refreshed:
self.write_to_cache()
if self.args.pretty:
print json.dumps(json_data, sort_keys=True, indent=2)
else:
print json.dumps(json_data)
# That's all she wrote...
###########################################################################
# Script configuration
###########################################################################
def read_settings(self):
""" Reads the settings from the digital_ocean.ini file """
config = ConfigParser.SafeConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + "/digital_ocean.ini")
# Credentials
if config.has_option("digital_ocean", "api_token"):
self.api_token = config.get("digital_ocean", "api_token")
# Cache related
if config.has_option("digital_ocean", "cache_path"):
#.........这里部分代码省略.........
示例14: DoManager
"""
dependencias:
sudo pip install dopy pyopenssl ndg-httpsclient pyasn1
"""
import os
from dopy.manager import DoManager
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
cliend_id = os.getenv("DO_CLIENT_ID")
api_key=os.getenv("DO_API_KEY")
do = DoManager(cliend_id, api_key)
keys = do.all_ssh_keys()
print "Nome da chave ssh\tid"
for key in keys:
print "%s\t%d" % (key["name"], key["id"])
print "Nome da imagem\tid"
imgs = do.all_images()
for img in imgs:
if img["slug"] == "ubuntu-14-04-x64":
print "%s\t%d" % (img["name"], img["id"])
print "Nome da regiao\tid"
regions = do.all_regions()
for region in regions:
if region["slug"] == "nyc2":