repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/cloud/clouds/proxmox.py
get_vmconfig
python
def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data
Get VM configuration
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1059-L1073
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def query(conn_type, option, post_data=None):\n '''\n Execute the HTTP request to the API\n '''\n if ticket is None or csrf is None or url is None:\n log.debug('Not authenticated yet, doing that now..')\n _authenticate()\n\n full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)\n\n log.debug('%s: %s (%s)', conn_type, full_url, post_data)\n\n httpheaders = {'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'salt-cloud-proxmox'}\n\n if conn_type == 'post':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.post(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'put':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.put(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'delete':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.delete(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'get':\n response = requests.get(full_url, verify=verify_ssl,\n cookies=ticket)\n\n response.raise_for_status()\n\n try:\n returned_data = response.json()\n if 'data' not in returned_data:\n raise SaltCloudExecutionFailure\n return returned_data['data']\n except Exception:\n log.error('Error in trying to process JSON')\n log.error(response)\n", "def avail_locations(call=None):\n '''\n Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-locations my-proxmox-config\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_locations function must be called with '\n '-f or --function, or with the --list-locations option'\n )\n\n # could also use the get_resources_nodes but speed is ~the same\n nodes = query('get', 'nodes')\n\n ret = {}\n for node in nodes:\n name = node['node']\n ret[name] = node\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
wait_for_state
python
def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state)
Wait until a specific state has been reached on a node
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1098-L1119
[ "def get_vm_status(vmid=None, name=None):\n '''\n Get the status for a VM, either via the ID or the hostname\n '''\n if vmid is not None:\n log.debug('get_vm_status: VMID %s', vmid)\n vmobj = _get_vm_by_id(vmid)\n elif name is not None:\n log.debug('get_vm_status: name %s', name)\n vmobj = _get_vm_by_name(name)\n else:\n log.debug(\"get_vm_status: No ID or NAME given\")\n raise SaltCloudExecutionFailure\n\n log.debug('VM found: %s', vmobj)\n\n if vmobj is not None and 'node' in vmobj:\n log.debug(\"VM_STATUS: Has desired info. Retrieving.. (%s)\",\n vmobj['name'])\n data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format(\n vmobj['node'], vmobj['type'], vmobj['vmid']))\n return data\n\n log.error('VM or requested status not found..')\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
wait_for_task
python
def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid)
Wait until a the task has been finished successfully
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1122-L1141
[ "def _lookup_proxmox_task(upid):\n '''\n Retrieve the (latest) logs and retrieve the status for a UPID.\n This can be used to verify whether a task has completed.\n '''\n log.debug('Getting creation status for upid: %s', upid)\n tasks = query('get', 'cluster/tasks')\n\n if tasks:\n for task in tasks:\n if task['upid'] == upid:\n log.debug('Found upid task: %s', task)\n return task\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
destroy
python
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)}
Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1144-L1198
[ "def stop(name, vmid=None, call=None):\n '''\n Stop a node (\"pulling the plug\").\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a stop mymachine\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The stop action must be called with -a or --action.'\n )\n\n if not set_vm_status('stop', name, vmid=vmid):\n log.error('Unable to bring VM %s (%s) down..', name, vmid)\n raise SaltCloudExecutionFailure\n\n # xxx: TBD: Check here whether the status was actually changed to 'stopped'\n\n return {'Stopped': '{0} was stopped.'.format(name)}\n", "def query(conn_type, option, post_data=None):\n '''\n Execute the HTTP request to the API\n '''\n if ticket is None or csrf is None or url is None:\n log.debug('Not authenticated yet, doing that now..')\n _authenticate()\n\n full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)\n\n log.debug('%s: %s (%s)', conn_type, full_url, post_data)\n\n httpheaders = {'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'salt-cloud-proxmox'}\n\n if conn_type == 'post':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.post(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'put':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.put(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'delete':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.delete(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'get':\n response = requests.get(full_url, verify=verify_ssl,\n cookies=ticket)\n\n response.raise_for_status()\n\n try:\n returned_data = response.json()\n if 'data' not in returned_data:\n raise SaltCloudExecutionFailure\n return returned_data['data']\n except Exception:\n log.error('Error in trying to process JSON')\n log.error(response)\n", "def _get_vm_by_name(name, allDetails=False):\n '''\n Since Proxmox works based op id's rather than names as identifiers this\n requires some filtering to retrieve the required information.\n '''\n vms = get_resources_vms(includeConfig=allDetails)\n if name in vms:\n return vms[name]\n\n log.info('VM with name \"%s\" could not be found.', name)\n return False\n", "def wait_for_state(vmid, state, timeout=300):\n '''\n Wait until a specific state has been reached on a node\n '''\n start_time = time.time()\n node = get_vm_status(vmid=vmid)\n if not node:\n log.error('wait_for_state: No VM retrieved based on given criteria.')\n raise SaltCloudExecutionFailure\n\n while True:\n if node['status'] == state:\n log.debug('Host %s is now in \"%s\" state!', node['name'], state)\n return True\n time.sleep(1)\n if time.time() - start_time > timeout:\n log.debug('Timeout reached while waiting for %s to become %s',\n node['name'], state)\n return False\n node = get_vm_status(vmid=vmid)\n log.debug('State for %s is: \"%s\" instead of \"%s\"',\n node['name'], node['status'], state)\n", "def get_vm_status(vmid=None, name=None):\n '''\n Get the status for a VM, either via the ID or the hostname\n '''\n if vmid is not None:\n log.debug('get_vm_status: VMID %s', vmid)\n vmobj = _get_vm_by_id(vmid)\n elif name is not None:\n log.debug('get_vm_status: name %s', name)\n vmobj = _get_vm_by_name(name)\n else:\n log.debug(\"get_vm_status: No ID or NAME given\")\n raise SaltCloudExecutionFailure\n\n log.debug('VM found: %s', vmobj)\n\n if vmobj is not None and 'node' in vmobj:\n log.debug(\"VM_STATUS: Has desired info. Retrieving.. (%s)\",\n vmobj['name'])\n data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format(\n vmobj['node'], vmobj['type'], vmobj['vmid']))\n return data\n\n log.error('VM or requested status not found..')\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
set_vm_status
python
def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False
Convenience function for setting VM status
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1201-L1231
[ "def query(conn_type, option, post_data=None):\n '''\n Execute the HTTP request to the API\n '''\n if ticket is None or csrf is None or url is None:\n log.debug('Not authenticated yet, doing that now..')\n _authenticate()\n\n full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)\n\n log.debug('%s: %s (%s)', conn_type, full_url, post_data)\n\n httpheaders = {'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'salt-cloud-proxmox'}\n\n if conn_type == 'post':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.post(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'put':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.put(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'delete':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.delete(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'get':\n response = requests.get(full_url, verify=verify_ssl,\n cookies=ticket)\n\n response.raise_for_status()\n\n try:\n returned_data = response.json()\n if 'data' not in returned_data:\n raise SaltCloudExecutionFailure\n return returned_data['data']\n except Exception:\n log.error('Error in trying to process JSON')\n log.error(response)\n", "def _get_vm_by_name(name, allDetails=False):\n '''\n Since Proxmox works based op id's rather than names as identifiers this\n requires some filtering to retrieve the required information.\n '''\n vms = get_resources_vms(includeConfig=allDetails)\n if name in vms:\n return vms[name]\n\n log.info('VM with name \"%s\" could not be found.', name)\n return False\n", "def _get_vm_by_id(vmid, allDetails=False):\n '''\n Retrieve a VM based on the ID.\n '''\n for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):\n if six.text_type(vm_details['vmid']) == six.text_type(vmid):\n return vm_details\n\n log.info('VM with ID \"%s\" could not be found.', vmid)\n return False\n", "def _parse_proxmox_upid(node, vm_=None):\n '''\n Upon requesting a task that runs for a longer period of time a UPID is given.\n This includes information about the job and can be used to lookup information in the log.\n '''\n ret = {}\n\n upid = node\n # Parse node response\n node = node.split(':')\n if node[0] == 'UPID':\n ret['node'] = six.text_type(node[1])\n ret['pid'] = six.text_type(node[2])\n ret['pstart'] = six.text_type(node[3])\n ret['starttime'] = six.text_type(node[4])\n ret['type'] = six.text_type(node[5])\n ret['vmid'] = six.text_type(node[6])\n ret['user'] = six.text_type(node[7])\n # include the upid again in case we'll need it again\n ret['upid'] = six.text_type(upid)\n\n if vm_ is not None and 'technology' in vm_:\n ret['technology'] = six.text_type(vm_['technology'])\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
get_vm_status
python
def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False
Get the status for a VM, either via the ID or the hostname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1234-L1258
[ "def query(conn_type, option, post_data=None):\n '''\n Execute the HTTP request to the API\n '''\n if ticket is None or csrf is None or url is None:\n log.debug('Not authenticated yet, doing that now..')\n _authenticate()\n\n full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)\n\n log.debug('%s: %s (%s)', conn_type, full_url, post_data)\n\n httpheaders = {'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'salt-cloud-proxmox'}\n\n if conn_type == 'post':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.post(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'put':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.put(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'delete':\n httpheaders['CSRFPreventionToken'] = csrf\n response = requests.delete(full_url, verify=verify_ssl,\n data=post_data,\n cookies=ticket,\n headers=httpheaders)\n elif conn_type == 'get':\n response = requests.get(full_url, verify=verify_ssl,\n cookies=ticket)\n\n response.raise_for_status()\n\n try:\n returned_data = response.json()\n if 'data' not in returned_data:\n raise SaltCloudExecutionFailure\n return returned_data['data']\n except Exception:\n log.error('Error in trying to process JSON')\n log.error(response)\n", "def _get_vm_by_name(name, allDetails=False):\n '''\n Since Proxmox works based op id's rather than names as identifiers this\n requires some filtering to retrieve the required information.\n '''\n vms = get_resources_vms(includeConfig=allDetails)\n if name in vms:\n return vms[name]\n\n log.info('VM with name \"%s\" could not be found.', name)\n return False\n", "def _get_vm_by_id(vmid, allDetails=False):\n '''\n Retrieve a VM based on the ID.\n '''\n for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):\n if six.text_type(vm_details['vmid']) == six.text_type(vmid):\n return vm_details\n\n log.info('VM with ID \"%s\" could not be found.', vmid)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
start
python
def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)}
Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1261-L1283
[ "def set_vm_status(status, name=None, vmid=None):\n '''\n Convenience function for setting VM status\n '''\n log.debug('Set status to %s for %s (%s)', status, name, vmid)\n\n if vmid is not None:\n log.debug('set_vm_status: via ID - VMID %s (%s): %s',\n vmid, name, status)\n vmobj = _get_vm_by_id(vmid)\n else:\n log.debug('set_vm_status: via name - VMID %s (%s): %s',\n vmid, name, status)\n vmobj = _get_vm_by_name(name)\n\n if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj:\n log.error('Unable to set status %s for %s (%s)',\n status, name, vmid)\n raise SaltCloudExecutionTimeout\n\n log.debug(\"VM_STATUS: Has desired info (%s). Setting status..\", vmobj)\n data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format(\n vmobj['node'], vmobj['type'], vmobj['vmid'], status))\n\n result = _parse_proxmox_upid(data, vmobj)\n\n if result is not False and result is not None:\n log.debug('Set_vm_status action result: %s', result)\n return True\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/cloud/clouds/proxmox.py
stop
python
def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if not set_vm_status('stop', name, vmid=vmid): log.error('Unable to bring VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Stopped': '{0} was stopped.'.format(name)}
Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L1286-L1307
[ "def set_vm_status(status, name=None, vmid=None):\n '''\n Convenience function for setting VM status\n '''\n log.debug('Set status to %s for %s (%s)', status, name, vmid)\n\n if vmid is not None:\n log.debug('set_vm_status: via ID - VMID %s (%s): %s',\n vmid, name, status)\n vmobj = _get_vm_by_id(vmid)\n else:\n log.debug('set_vm_status: via name - VMID %s (%s): %s',\n vmid, name, status)\n vmobj = _get_vm_by_name(name)\n\n if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj:\n log.error('Unable to set status %s for %s (%s)',\n status, name, vmid)\n raise SaltCloudExecutionTimeout\n\n log.debug(\"VM_STATUS: Has desired info (%s). Setting status..\", vmobj)\n data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format(\n vmobj['node'], vmobj['type'], vmobj['vmid'], status))\n\n result = _parse_proxmox_upid(data, vmobj)\n\n if result is not False and result is not None:\n log.debug('Set_vm_status action result: %s', result)\n return True\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Proxmox Cloud Module ====================== .. versionadded:: 2014.7.0 The Proxmox cloud module is used to control access to cloud providers using the Proxmox system (KVM / OpenVZ / LXC). Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/proxmox.conf``: .. code-block:: yaml my-proxmox-config: # Proxmox account information user: myuser@pam or myuser@pve password: mypassword url: hypervisor.domain.tld port: 8006 driver: proxmox verify_ssl: True :maintainer: Frank Klaassen <frank@cloudright.nl> :depends: requests >= 2.2.1 :depends: IPy >= 0.81 ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import time import pprint import logging import re # Import salt libs import salt.utils.cloud import salt.utils.json # Import salt cloud libs import salt.config as config from salt.exceptions import ( SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) # Import 3rd-party Libs from salt.ext import six from salt.ext.six.moves import range try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from IPy import IP HAS_IPY = True except ImportError: HAS_IPY = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'proxmox' def __virtual__(): ''' Check for PROXMOX configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('user',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' deps = { 'requests': HAS_REQUESTS, 'IPy': HAS_IPY } return config.check_driver_dependencies( __virtualname__, deps ) url = None port = None ticket = None csrf = None verify_ssl = None api = None def _authenticate(): ''' Retrieve CSRF and API tickets for the Proxmox API ''' global url, port, ticket, csrf, verify_ssl url = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) port = config.get_cloud_config_value( 'port', get_configured_provider(), __opts__, default=8006, search_global=False ) username = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd = config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) verify_ssl = config.get_cloud_config_value( 'verify_ssl', get_configured_provider(), __opts__, default=True, search_global=False ) connect_data = {'username': username, 'password': passwd} full_url = 'https://{0}:{1}/api2/json/access/ticket'.format(url, port) returned_data = requests.post( full_url, verify=verify_ssl, data=connect_data).json() ticket = {'PVEAuthCookie': returned_data['data']['ticket']} csrf = six.text_type(returned_data['data']['CSRFPreventionToken']) def query(conn_type, option, post_data=None): ''' Execute the HTTP request to the API ''' if ticket is None or csrf is None or url is None: log.debug('Not authenticated yet, doing that now..') _authenticate() full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option) log.debug('%s: %s (%s)', conn_type, full_url, post_data) httpheaders = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'salt-cloud-proxmox'} if conn_type == 'post': httpheaders['CSRFPreventionToken'] = csrf response = requests.post(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'put': httpheaders['CSRFPreventionToken'] = csrf response = requests.put(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'delete': httpheaders['CSRFPreventionToken'] = csrf response = requests.delete(full_url, verify=verify_ssl, data=post_data, cookies=ticket, headers=httpheaders) elif conn_type == 'get': response = requests.get(full_url, verify=verify_ssl, cookies=ticket) response.raise_for_status() try: returned_data = response.json() if 'data' not in returned_data: raise SaltCloudExecutionFailure return returned_data['data'] except Exception: log.error('Error in trying to process JSON') log.error(response) def _get_vm_by_name(name, allDetails=False): ''' Since Proxmox works based op id's rather than names as identifiers this requires some filtering to retrieve the required information. ''' vms = get_resources_vms(includeConfig=allDetails) if name in vms: return vms[name] log.info('VM with name "%s" could not be found.', name) return False def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could not be found.', vmid) return False def _get_next_vmid(): ''' Proxmox allows the use of alternative ids instead of autoincrementing. Because of that its required to query what the first available ID is. ''' return int(query('get', 'cluster/nextid')) def _check_ip_available(ip_addr): ''' Proxmox VMs refuse to start when the IP is already being used. This function can be used to prevent VMs being created with duplicate IP's or to generate a warning. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): vm_config = vm_details['config'] if ip_addr in vm_config['ip_address'] or vm_config['ip_address'] == ip_addr: log.debug('IP "%s" is already defined', ip_addr) return False log.debug('IP \'%s\' is available to be defined', ip_addr) return True def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') if node[0] == 'UPID': ret['node'] = six.text_type(node[1]) ret['pid'] = six.text_type(node[2]) ret['pstart'] = six.text_type(node[3]) ret['starttime'] = six.text_type(node[4]) ret['type'] = six.text_type(node[5]) ret['vmid'] = six.text_type(node[6]) ret['user'] = six.text_type(node[7]) # include the upid again in case we'll need it again ret['upid'] = six.text_type(upid) if vm_ is not None and 'technology' in vm_: ret['technology'] = six.text_type(vm_['technology']) return ret def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: if task['upid'] == upid: log.debug('Found upid task: %s', task) return task return False def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} for resource in resources: if 'type' in resource and resource['type'] == 'node': name = resource['node'] ret[name] = resource if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def get_resources_vms(call=None, resFilter=None, includeConfig=True): ''' Retrieve all VMs available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_vms my-proxmox-config ''' timeoutTime = time.time() + 60 while True: log.debug('Getting resource: vms.. (filter: %s)', resFilter) resources = query('get', 'cluster/resources') ret = {} badResource = False for resource in resources: if 'type' in resource and resource['type'] in ['openvz', 'qemu', 'lxc']: try: name = resource['name'] except KeyError: badResource = True log.debug('No name in VM resource %s', repr(resource)) break ret[name] = resource if includeConfig: # Requested to include the detailed configuration of a VM ret[name]['config'] = get_vmconfig( ret[name]['vmid'], ret[name]['node'], ret[name]['type'] ) if time.time() > timeoutTime: raise SaltCloudExecutionTimeout('FAILED to get the proxmox ' 'resources vms') # Carry on if there wasn't a bad resource return from Proxmox if not badResource: break time.sleep(0.5) if resFilter is not None: log.debug('Filter given: %s, returning requested ' 'resource: nodes', resFilter) return ret[resFilter] log.debug('Filter not given: %s, returning all resource: nodes', ret) return ret def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.utils.cloud.minion_config(__opts__, vm_) ) ) def avail_locations(call=None): ''' Return a list of the hypervisors (nodes) which this Proxmox PVE machine manages CLI Example: .. code-block:: bash salt-cloud --list-locations my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) # could also use the get_resources_nodes but speed is ~the same nodes = query('get', 'nodes') ret = {} for node in nodes: name = node['node'] ret[name] = node return ret def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)): ret[item['volid']] = item return ret def list_nodes(call=None): ''' Return a list of the VMs that are managed by the provider CLI Example: .. code-block:: bash salt-cloud -Q my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)): log.debug('VM_Name: %s', vm_name) log.debug('vm_details: %s', vm_details) # Limit resultset on what Salt-cloud demands: ret[vm_name] = {} ret[vm_name]['id'] = six.text_type(vm_details['vmid']) ret[vm_name]['image'] = six.text_type(vm_details['vmid']) ret[vm_name]['size'] = six.text_type(vm_details['disk']) ret[vm_name]['state'] = six.text_type(vm_details['status']) # Figure out which is which to put it in the right column private_ips = [] public_ips = [] if 'ip_address' in vm_details['config'] and vm_details['config']['ip_address'] != '-': ips = vm_details['config']['ip_address'].split(' ') for ip_ in ips: if IP(ip_).iptype() == 'PRIVATE': private_ips.append(six.text_type(ip_)) else: public_ips.append(six.text_type(ip_)) ret[vm_name]['private_ips'] = private_ips ret[vm_name]['public_ips'] = public_ips return ret def list_nodes_full(call=None): ''' Return a list of the VMs that are on the provider CLI Example: .. code-block:: bash salt-cloud -F my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return get_resources_vms(includeConfig=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields CLI Example: .. code-block:: bash salt-cloud -S my-proxmox-config ''' return salt.utils.cloud.list_nodes_select( list_nodes_full(), __opts__['query.selection'], call, ) def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} for item in li: pair = str(item).replace(' ', '').split('=') if len(pair) != 2: log.warning('Cannot process stringlist item %s', item) continue ret[pair[0]] = pair[1] return ret def _dictionary_to_stringlist(input_dict): ''' Convert a dictionary to a stringlist (comma separated settings) The result of the dictionary {'setting1':'value1','setting2':'value2'} will be: setting1=value1,setting2=value2 ''' string_value = "" for s in input_dict: string_value += "{0}={1},".format(s, input_dict[s]) string_value = string_value[:-1] return string_value def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p proxmox-ubuntu vmhostname ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'proxmox', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass ret = {} __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) if 'use_dns' in vm_ and 'ip_address' not in vm_: use_dns = vm_['use_dns'] if use_dns: from socket import gethostbyname, gaierror try: ip_address = gethostbyname(six.text_type(vm_['name'])) except gaierror: log.debug('Resolving of %s failed', vm_['name']) else: vm_['ip_address'] = six.text_type(ip_address) try: newid = _get_next_vmid() data = create_node(vm_, newid) except Exception as exc: log.error( 'Error creating %s on PROXMOX\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False ret['creation_data'] = data name = vm_['name'] # hostname which we know if 'clone' in vm_ and vm_['clone'] is True: vmid = newid else: vmid = data['vmid'] # vmid which we have received host = data['node'] # host which we have received nodeType = data['technology'] # VM tech (Qemu / OpenVZ) if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0: # Determine which IP to use in order of preference: if 'ip_address' in vm_: ip_address = six.text_type(vm_['ip_address']) elif 'public_ips' in data: ip_address = six.text_type(data['public_ips'][0]) # first IP elif 'private_ips' in data: ip_address = six.text_type(data['private_ips'][0]) # first IP else: raise SaltCloudExecutionFailure("Could not determine an IP address to use") # wait until the vm has been created so we can start it if not wait_for_created(data['upid'], timeout=300): return {'Error': 'Unable to create {0}, command timed out'.format(name)} if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': # If we cloned a machine, see if we need to reconfigure any of the options such as net0, # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's # brought up log.info('Configuring cloned VM') # Modify the settings for the VM one at a time so we can see any problems with the values # as quickly as possible for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # cloud-init settings for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain': if setting in vm_: # if the property is set, use it for the VM request postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(3): setting = 'ide{0}'.format(setting_number) if setting in vm_: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(5): setting = 'sata{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(13): setting = 'scsi{0}'.format(setting_number) if setting in vm_: vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) if setting in vm_config: setting_params = vm_[setting] setting_storage = setting_params.split(':')[0] setting_size = _stringlist_to_dictionary(setting_params)['size'] vm_disk_params = vm_config[setting] vm_disk_storage = vm_disk_params.split(':')[0] vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size'] # if storage is different, move the disk if setting_storage != vm_disk_storage: postParams = {} postParams['disk'] = setting postParams['storage'] = setting_storage postParams['delete'] = 1 node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format( vm_['host'], vmid), postParams) data = _parse_proxmox_upid(node, vm_) # wait until the disk has been moved if not wait_for_task(data['upid'], timeout=300): return {'Error': 'Unable to move disk {0}, command timed out'.format( setting)} # if storage is different, move the disk if setting_size != vm_disk_size: postParams = {} postParams['disk'] = setting postParams['size'] = setting_size query('put', 'nodes/{0}/qemu/{1}/resize'.format( vm_['host'], vmid), postParams) else: postParams = {} postParams[setting] = vm_[setting] query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # net strings are a list of comma seperated settings. We need to merge the settings so that # the setting in the profile only changes the settings it touches and the other settings # are left alone. An example of why this is necessary is because the MAC address is set # in here and generally you don't want to alter or have to know the MAC address of the new # instance, but you may want to set the VLAN bridge for example for setting_number in range(20): setting = 'net{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) for setting_number in range(20): setting = 'ipconfig{0}'.format(setting_number) if setting in vm_: data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid)) # Generate a dictionary of settings from the existing string new_setting = {} if setting in data: new_setting.update(_stringlist_to_dictionary(data[setting])) # Merge the new settings (as a dictionary) into the existing dictionary to get the # new merged settings if setting_number == 0 and 'ip_address' in vm_: if 'gw' in _stringlist_to_dictionary(vm_[setting]): new_setting.update(_stringlist_to_dictionary( 'ip={0}/24,gw={1}'.format( vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw']))) else: new_setting.update( _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address']))) else: new_setting.update(_stringlist_to_dictionary(vm_[setting])) # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams) # VM has been created. Starting.. if not start(name, vmid, call='action'): log.error('Node %s (%s) failed to start!', name, vmid) raise SaltCloudExecutionFailure # Wait until the VM has fully started log.debug('Waiting for state "running" for vm %s on %s', vmid, host) if not wait_for_state(vmid, 'running'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} # For QEMU VMs, we can get the IP Address from qemu-agent if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1: def __find_agent_ip(vm_): log.debug("Waiting for qemu-agent to start...") endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid) interfaces = query('get', endpoint) # If we get a result from the agent, parse it if 'result' in interfaces: for interface in interfaces['result']: if_name = interface['name'] # Only check ethernet type interfaces, as they are not returned in any order if if_name.startswith('eth') or if_name.startswith('ens'): for if_addr in interface['ip-addresses']: ip_addr = if_addr['ip-address'] # Ensure interface has a valid IPv4 address if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None: return six.text_type(ip_addr) raise SaltCloudExecutionFailure # We have to wait for a bit for qemu-agent to start try: ip_address = __utils__['cloud.wait_for_fun']( __find_agent_ip, vm_=vm_ ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # If VM was created but we can't connect, destroy it. destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) log.debug('Using IP address %s', ip_address) ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) ssh_password = config.get_cloud_config_value( 'password', vm_, __opts__, ) ret['ip_address'] = ip_address ret['username'] = ssh_username ret['password'] = ssh_password vm_['ssh_host'] = ip_address vm_['password'] = ssh_password ret = __utils__['cloud.bootstrap'](vm_, __opts__) # Report success! log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']( 'created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def _import_api(): ''' Download https://<url>/pve-docs/api-viewer/apidoc.js Extract content of pveapi var (json formated) Load this json content into global variable "api" ''' global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js'.format(url, port) returned_data = requests.get(full_url, verify=verify_ssl) re_filter = re.compile('(?<=pveapi =)(.*)(?=^;)', re.DOTALL | re.MULTILINE) api_json = re_filter.findall(returned_data.text)[0] api = salt.utils.json.loads(api_json) def _get_properties(path="", method="GET", forced_params=None): ''' Return the parameter list from api for defined path and HTTP method ''' if api is None: _import_api() sub = api path_levels = [level for level in path.split('/') if level != ''] search_path = '' props = [] parameters = set([] if forced_params is None else forced_params) # Browse all path elements but last for elem in path_levels[:-1]: search_path += '/' + elem # Lookup for a dictionary with path = "requested path" in list" and return its children sub = (item for item in sub if item["path"] == search_path).next()['children'] # Get leaf element in path search_path += '/' + path_levels[-1] sub = next((item for item in sub if item["path"] == search_path)) try: # get list of properties for requested method props = sub['info'][method]['parameters']['properties'].keys() except KeyError as exc: log.error('method not found: "%s"', exc) for prop in props: numerical = re.match(r'(\w+)\[n\]', prop) # generate (arbitrarily) 10 properties for duplicatable properties identified by: # "prop[n]" if numerical: for i in range(10): parameters.add(numerical.group(1) + six.text_type(i)) else: parameters.add(prop) return parameters def create_node(vm_, newid): ''' Build and submit the requestdata to create a new node ''' newnode = {} if 'technology' not in vm_: vm_['technology'] = 'openvz' # default virt tech if none is given if vm_['technology'] not in ['qemu', 'openvz', 'lxc']: # Wrong VM type given log.error('Wrong VM type. Valid options are: qemu, openvz (proxmox3) or lxc (proxmox4)') raise SaltCloudExecutionFailure if 'host' not in vm_: # Use globally configured/default location vm_['host'] = config.get_cloud_config_value( 'default_host', get_configured_provider(), __opts__, search_global=False ) if vm_['host'] is None: # No location given for the profile log.error('No host given to create this VM on') raise SaltCloudExecutionFailure # Required by both OpenVZ and Qemu (KVM) vmhost = vm_['host'] newnode['vmid'] = newid for prop in 'cpuunits', 'description', 'memory', 'onboot': if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if vm_['technology'] == 'openvz': # OpenVZ related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] # optional VZ settings for prop in ['cpus', 'disk', 'ip_address', 'nameserver', 'password', 'swap', 'poolid', 'storage']: if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] elif vm_['technology'] == 'lxc': # LXC related settings, using non-default names: newnode['hostname'] = vm_['name'] newnode['ostemplate'] = vm_['image'] static_props = ('cpuunits', 'cpulimit', 'rootfs', 'cores', 'description', 'memory', 'onboot', 'net0', 'password', 'nameserver', 'swap', 'storage', 'rootfs') for prop in _get_properties('/nodes/{node}/lxc', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] if 'pubkey' in vm_: newnode['ssh-public-keys'] = vm_['pubkey'] # inform user the "disk" option is not supported for LXC hosts if 'disk' in vm_: log.warning('The "disk" option is not supported for LXC hosts and was ignored') # LXC specific network config # OpenVZ allowed specifying IP and gateway. To ease migration from # Proxmox 3, I've mapped the ip_address and gw to a generic net0 config. # If you need more control, please use the net0 option directly. # This also assumes a /24 subnet. if 'ip_address' in vm_ and 'net0' not in vm_: newnode['net0'] = 'bridge=vmbr0,ip=' + vm_['ip_address'] + '/24,name=eth0,type=veth' # gateway is optional and does not assume a default if 'gw' in vm_: newnode['net0'] = newnode['net0'] + ',gw=' + vm_['gw'] elif vm_['technology'] == 'qemu': # optional Qemu settings static_props = ( 'acpi', 'cores', 'cpu', 'pool', 'storage', 'sata0', 'ostype', 'ide2', 'net0') for prop in _get_properties('/nodes/{node}/qemu', 'POST', static_props): if prop in vm_: # if the property is set, use it for the VM request newnode[prop] = vm_[prop] # The node is ready. Lets request it to be added __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', newnode, list(newnode)), }, sock_dir=__opts__['sock_dir'], ) log.debug('Preparing to generate a node using these parameters: %s ', newnode) if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu': postParams = {} postParams['newid'] = newnode['vmid'] for prop in 'description', 'format', 'full', 'name': if 'clone_' + prop in vm_: # if the property is set, use it for the VM request postParams[prop] = vm_['clone_' + prop] if 'host' in vm_: postParams['target'] = vm_['host'] try: int(vm_['clone_from']) except ValueError: if ':' in vm_['clone_from']: vmhost = vm_['clone_from'].split(':')[0] vm_['clone_from'] = vm_['clone_from'].split(':')[1] node = query('post', 'nodes/{0}/qemu/{1}/clone'.format( vmhost, vm_['clone_from']), postParams) else: node = query('post', 'nodes/{0}/{1}'.format(vmhost, vm_['technology']), newnode) return _parse_proxmox_upid(node, vm_) def show_instance(name, call=None): ''' Show the details from Proxmox concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__) return nodes[name] def get_vmconfig(vmid, node=None, node_type='openvz'): ''' Get VM configuration ''' if node is None: # We need to figure out which node this VM is on. for host_name, host_details in six.iteritems(avail_locations()): for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)): if item['vmid'] == vmid: node = host_name # If we reached this point, we have all the information we need data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid)) return data def wait_for_created(upid, timeout=300): ''' Wait until a the vm has been created successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_created: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Host has been created!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for host to be created') return False info = _lookup_proxmox_task(upid) def wait_for_state(vmid, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = get_vm_status(vmid=vmid) if not node: log.error('wait_for_state: No VM retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if node['status'] == state: log.debug('Host %s is now in "%s" state!', node['name'], state) return True time.sleep(1) if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for %s to become %s', node['name'], state) return False node = get_vm_status(vmid=vmid) log.debug('State for %s is: "%s" instead of "%s"', node['name'], node['status'], state) def wait_for_task(upid, timeout=300): ''' Wait until a the task has been finished successfully ''' start_time = time.time() info = _lookup_proxmox_task(upid) if not info: log.error('wait_for_task: No task information ' 'retrieved based on given criteria.') raise SaltCloudExecutionFailure while True: if 'status' in info and info['status'] == 'OK': log.debug('Task has been finished!') return True time.sleep(3) # Little more patience, we're not in a hurry if time.time() - start_time > timeout: log.debug('Timeout reached while waiting for task to be finished') return False info = _lookup_proxmox_task(upid) def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vmobj = _get_vm_by_name(name) if vmobj is not None: # stop the vm if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped': stop(name, vmobj['vmid'], 'action') # wait until stopped if not wait_for_state(vmobj['vmid'], 'stopped'): return {'Error': 'Unable to stop {0}, command timed out'.format(name)} # required to wait a bit here, otherwise the VM is sometimes # still locked and destroy fails. time.sleep(3) query('delete', 'nodes/{0}/{1}'.format( vmobj['node'], vmobj['id'] )) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)} def set_vm_status(status, name=None, vmid=None): ''' Convenience function for setting VM status ''' log.debug('Set status to %s for %s (%s)', status, name, vmid) if vmid is not None: log.debug('set_vm_status: via ID - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_id(vmid) else: log.debug('set_vm_status: via name - VMID %s (%s): %s', vmid, name, status) vmobj = _get_vm_by_name(name) if not vmobj or 'node' not in vmobj or 'type' not in vmobj or 'vmid' not in vmobj: log.error('Unable to set status %s for %s (%s)', status, name, vmid) raise SaltCloudExecutionTimeout log.debug("VM_STATUS: Has desired info (%s). Setting status..", vmobj) data = query('post', 'nodes/{0}/{1}/{2}/status/{3}'.format( vmobj['node'], vmobj['type'], vmobj['vmid'], status)) result = _parse_proxmox_upid(data, vmobj) if result is not False and result is not None: log.debug('Set_vm_status action result: %s', result) return True return False def get_vm_status(vmid=None, name=None): ''' Get the status for a VM, either via the ID or the hostname ''' if vmid is not None: log.debug('get_vm_status: VMID %s', vmid) vmobj = _get_vm_by_id(vmid) elif name is not None: log.debug('get_vm_status: name %s', name) vmobj = _get_vm_by_name(name) else: log.debug("get_vm_status: No ID or NAME given") raise SaltCloudExecutionFailure log.debug('VM found: %s', vmobj) if vmobj is not None and 'node' in vmobj: log.debug("VM_STATUS: Has desired info. Retrieving.. (%s)", vmobj['name']) data = query('get', 'nodes/{0}/{1}/{2}/status/current'.format( vmobj['node'], vmobj['type'], vmobj['vmid'])) return data log.error('VM or requested status not found..') return False def start(name, vmid=None, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.debug('Start: %s (%s) = Start', name, vmid) if not set_vm_status('start', name, vmid=vmid): log.error('Unable to bring VM %s (%s) up..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'started' return {'Started': '{0} was started.'.format(name)} def shutdown(name=None, vmid=None, call=None): ''' Shutdown a node via ACPI. CLI Example: .. code-block:: bash salt-cloud -a shutdown mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The shutdown action must be called with -a or --action.' ) if not set_vm_status('shutdown', name, vmid=vmid): log.error('Unable to shut VM %s (%s) down..', name, vmid) raise SaltCloudExecutionFailure # xxx: TBD: Check here whether the status was actually changed to 'stopped' return {'Shutdown': '{0} was shutdown.'.format(name)}
saltstack/salt
salt/states/rsync.py
_get_summary
python
def _get_summary(rsync_out): ''' Get summary from the rsync successful output. ''' return "- " + "\n- ".join([elm for elm in rsync_out.split("\n\n")[-1].replace(" ", "\n").split("\n") if elm])
Get summary from the rsync successful output.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L48-L53
null
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' State to synchronize files and directories with rsync. .. versionadded:: 2016.3.0 .. code-block:: yaml /opt/user-backups: rsync.synchronized: - source: /home - force: True ''' from __future__ import absolute_import, print_function, unicode_literals import logging import os import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only if Rsync is available. :return: ''' return salt.utils.path.which('rsync') and 'rsync' or False def _get_changes(rsync_out): ''' Get changes from the rsync successful output. ''' copied = list() deleted = list() for line in rsync_out.split("\n\n")[0].split("\n")[1:]: if line.startswith("deleting "): deleted.append(line.split(" ", 1)[-1]) else: copied.append(line) ret = { 'copied': os.linesep.join(sorted(copied)) or "N/A", 'deleted': os.linesep.join(sorted(deleted)) or "N/A", } # Return whether anything really changed ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A')) return ret def synchronized(name, source, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, prepare=False, dryrun=False, additional_opts=None): ''' Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not os.path.exists(name) and not force and not prepare: ret['result'] = False ret['comment'] = "Destination directory {dest} was not found.".format(dest=name) else: if not os.path.exists(name) and prepare: os.makedirs(name) if __opts__['test']: dryrun = True result = __salt__['rsync.rsync'](source, name, delete=delete, force=force, update=update, passwordfile=passwordfile, exclude=exclude, excludefrom=excludefrom, dryrun=dryrun, additional_opts=additional_opts) if __opts__['test'] or dryrun: ret['result'] = None ret['comment'] = _get_summary(result['stdout']) return ret # Failed if result.get('retcode'): ret['result'] = False ret['comment'] = result['stderr'] # Changed elif _get_changes(result['stdout'])['changed']: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = _get_changes(result['stdout']) del ret['changes']['changed'] # Don't need to print the boolean # Clean else: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = {} return ret
saltstack/salt
salt/states/rsync.py
_get_changes
python
def _get_changes(rsync_out): ''' Get changes from the rsync successful output. ''' copied = list() deleted = list() for line in rsync_out.split("\n\n")[0].split("\n")[1:]: if line.startswith("deleting "): deleted.append(line.split(" ", 1)[-1]) else: copied.append(line) ret = { 'copied': os.linesep.join(sorted(copied)) or "N/A", 'deleted': os.linesep.join(sorted(deleted)) or "N/A", } # Return whether anything really changed ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A')) return ret
Get changes from the rsync successful output.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L56-L77
null
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' State to synchronize files and directories with rsync. .. versionadded:: 2016.3.0 .. code-block:: yaml /opt/user-backups: rsync.synchronized: - source: /home - force: True ''' from __future__ import absolute_import, print_function, unicode_literals import logging import os import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only if Rsync is available. :return: ''' return salt.utils.path.which('rsync') and 'rsync' or False def _get_summary(rsync_out): ''' Get summary from the rsync successful output. ''' return "- " + "\n- ".join([elm for elm in rsync_out.split("\n\n")[-1].replace(" ", "\n").split("\n") if elm]) def synchronized(name, source, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, prepare=False, dryrun=False, additional_opts=None): ''' Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not os.path.exists(name) and not force and not prepare: ret['result'] = False ret['comment'] = "Destination directory {dest} was not found.".format(dest=name) else: if not os.path.exists(name) and prepare: os.makedirs(name) if __opts__['test']: dryrun = True result = __salt__['rsync.rsync'](source, name, delete=delete, force=force, update=update, passwordfile=passwordfile, exclude=exclude, excludefrom=excludefrom, dryrun=dryrun, additional_opts=additional_opts) if __opts__['test'] or dryrun: ret['result'] = None ret['comment'] = _get_summary(result['stdout']) return ret # Failed if result.get('retcode'): ret['result'] = False ret['comment'] = result['stderr'] # Changed elif _get_changes(result['stdout'])['changed']: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = _get_changes(result['stdout']) del ret['changes']['changed'] # Don't need to print the boolean # Clean else: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = {} return ret
saltstack/salt
salt/states/rsync.py
synchronized
python
def synchronized(name, source, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, prepare=False, dryrun=False, additional_opts=None): ''' Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0 ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not os.path.exists(name) and not force and not prepare: ret['result'] = False ret['comment'] = "Destination directory {dest} was not found.".format(dest=name) else: if not os.path.exists(name) and prepare: os.makedirs(name) if __opts__['test']: dryrun = True result = __salt__['rsync.rsync'](source, name, delete=delete, force=force, update=update, passwordfile=passwordfile, exclude=exclude, excludefrom=excludefrom, dryrun=dryrun, additional_opts=additional_opts) if __opts__['test'] or dryrun: ret['result'] = None ret['comment'] = _get_summary(result['stdout']) return ret # Failed if result.get('retcode'): ret['result'] = False ret['comment'] = result['stderr'] # Changed elif _get_changes(result['stdout'])['changed']: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = _get_changes(result['stdout']) del ret['changes']['changed'] # Don't need to print the boolean # Clean else: ret['comment'] = _get_summary(result['stdout']) ret['changes'] = {} return ret
Guarantees that the source directory is always copied to the target. name Name of the target directory. source Source directory. prepare Create destination directory if it does not exists. delete Delete extraneous files from the destination dirs (True or False) force Force deletion of dirs even if not empty update Skip files that are newer on the receiver (True or False) passwordfile Read daemon-access password from the file (path) exclude Exclude files, that matches pattern. excludefrom Read exclude patterns from the file (path) dryrun Perform a trial run with no changes made. Is the same as doing test=True .. versionadded:: 2016.3.1 additional_opts Pass additional options to rsync, should be included as a list. .. versionadded:: 2018.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rsync.py#L80-L170
[ "def _get_changes(rsync_out):\n '''\n Get changes from the rsync successful output.\n '''\n copied = list()\n deleted = list()\n\n for line in rsync_out.split(\"\\n\\n\")[0].split(\"\\n\")[1:]:\n if line.startswith(\"deleting \"):\n deleted.append(line.split(\" \", 1)[-1])\n else:\n copied.append(line)\n\n ret = {\n 'copied': os.linesep.join(sorted(copied)) or \"N/A\",\n 'deleted': os.linesep.join(sorted(deleted)) or \"N/A\",\n }\n\n # Return whether anything really changed\n ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A'))\n\n return ret\n", "def _get_summary(rsync_out):\n '''\n Get summary from the rsync successful output.\n '''\n\n return \"- \" + \"\\n- \".join([elm for elm in rsync_out.split(\"\\n\\n\")[-1].replace(\" \", \"\\n\").split(\"\\n\") if elm])\n" ]
# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' State to synchronize files and directories with rsync. .. versionadded:: 2016.3.0 .. code-block:: yaml /opt/user-backups: rsync.synchronized: - source: /home - force: True ''' from __future__ import absolute_import, print_function, unicode_literals import logging import os import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only if Rsync is available. :return: ''' return salt.utils.path.which('rsync') and 'rsync' or False def _get_summary(rsync_out): ''' Get summary from the rsync successful output. ''' return "- " + "\n- ".join([elm for elm in rsync_out.split("\n\n")[-1].replace(" ", "\n").split("\n") if elm]) def _get_changes(rsync_out): ''' Get changes from the rsync successful output. ''' copied = list() deleted = list() for line in rsync_out.split("\n\n")[0].split("\n")[1:]: if line.startswith("deleting "): deleted.append(line.split(" ", 1)[-1]) else: copied.append(line) ret = { 'copied': os.linesep.join(sorted(copied)) or "N/A", 'deleted': os.linesep.join(sorted(deleted)) or "N/A", } # Return whether anything really changed ret['changed'] = not ((ret['copied'] == 'N/A') and (ret['deleted'] == 'N/A')) return ret
saltstack/salt
salt/modules/cisconso.py
get_data
python
def get_data(datastore, path): ''' Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data running 'devices/ex0' ''' if isinstance(path, six.string_types): path = '/'.split(path) return _proxy_cmd('get_data', datastore, path)
Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data running 'devices/ex0'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cisconso.py#L37-L58
[ "def _proxy_cmd(command, *args, **kwargs):\n '''\n run commands from __proxy__\n :mod:`salt.proxy.cisconso<salt.proxy.cisconso>`\n\n command\n function from `salt.proxy.cisconso` to run\n\n args\n positional args to pass to `command` function\n\n kwargs\n key word arguments to pass to `command` function\n '''\n proxy_prefix = __opts__['proxy']['proxytype']\n proxy_cmd = '.'.join([proxy_prefix, command])\n if proxy_cmd not in __proxy__:\n return False\n for k in kwargs:\n if k.startswith('__pub_'):\n kwargs.pop(k)\n return __proxy__[proxy_cmd](*args, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco Network Services Orchestrator Proxy minions .. versionadded: 2016.11.0 For documentation on setting up the cisconso proxy minion look in the documentation for :mod:`salt.proxy.cisconso<salt.proxy.cisconso>`. ''' from __future__ import absolute_import, print_function, unicode_literals import salt.utils.platform from salt.ext import six __proxyenabled__ = ['cisconso'] __virtualname__ = 'cisconso' def __virtual__(): if salt.utils.platform.is_proxy(): return __virtualname__ return (False, 'The cisconso execution module failed to load: ' 'only available on proxy minions.') def info(): ''' Return system information for grains of the NSO proxy minion .. code-block:: bash salt '*' cisconso.info ''' return _proxy_cmd('info') def set_data_value(datastore, path, data): ''' Set a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. .. code-block:: bash salt cisco-nso cisconso.set_data_value running 'devices/ex0/routes' 10.0.0.20/24 ''' if isinstance(path, six.string_types): path = '/'.split(path) return _proxy_cmd('set_data_value', datastore, path, data) def get_rollbacks(): ''' Get a list of stored configuration rollbacks .. code-block:: bash salt cisco-nso cisconso.get_rollbacks ''' return _proxy_cmd('get_rollbacks') def get_rollback(name): ''' Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot .. code-block:: bash salt cisco-nso cisconso.get_rollback 52 ''' return _proxy_cmd('get_rollback', name) def apply_rollback(datastore, name): ''' Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` .. code-block:: bash salt cisco-nso cisconso.apply_rollback 52 ''' return _proxy_cmd('apply_rollback', datastore, name) def _proxy_cmd(command, *args, **kwargs): ''' run commands from __proxy__ :mod:`salt.proxy.cisconso<salt.proxy.cisconso>` command function from `salt.proxy.cisconso` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function ''' proxy_prefix = __opts__['proxy']['proxytype'] proxy_cmd = '.'.join([proxy_prefix, command]) if proxy_cmd not in __proxy__: return False for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) return __proxy__[proxy_cmd](*args, **kwargs)
saltstack/salt
salt/modules/cisconso.py
set_data_value
python
def set_data_value(datastore, path, data): ''' Set a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. .. code-block:: bash salt cisco-nso cisconso.set_data_value running 'devices/ex0/routes' 10.0.0.20/24 ''' if isinstance(path, six.string_types): path = '/'.split(path) return _proxy_cmd('set_data_value', datastore, path, data)
Set a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :param data: The new value at the given path :type data: ``dict`` :rtype: ``bool`` :return: ``True`` if successful, otherwise error. .. code-block:: bash salt cisco-nso cisconso.set_data_value running 'devices/ex0/routes' 10.0.0.20/24
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cisconso.py#L61-L85
[ "def _proxy_cmd(command, *args, **kwargs):\n '''\n run commands from __proxy__\n :mod:`salt.proxy.cisconso<salt.proxy.cisconso>`\n\n command\n function from `salt.proxy.cisconso` to run\n\n args\n positional args to pass to `command` function\n\n kwargs\n key word arguments to pass to `command` function\n '''\n proxy_prefix = __opts__['proxy']['proxytype']\n proxy_cmd = '.'.join([proxy_prefix, command])\n if proxy_cmd not in __proxy__:\n return False\n for k in kwargs:\n if k.startswith('__pub_'):\n kwargs.pop(k)\n return __proxy__[proxy_cmd](*args, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Execution module for Cisco Network Services Orchestrator Proxy minions .. versionadded: 2016.11.0 For documentation on setting up the cisconso proxy minion look in the documentation for :mod:`salt.proxy.cisconso<salt.proxy.cisconso>`. ''' from __future__ import absolute_import, print_function, unicode_literals import salt.utils.platform from salt.ext import six __proxyenabled__ = ['cisconso'] __virtualname__ = 'cisconso' def __virtual__(): if salt.utils.platform.is_proxy(): return __virtualname__ return (False, 'The cisconso execution module failed to load: ' 'only available on proxy minions.') def info(): ''' Return system information for grains of the NSO proxy minion .. code-block:: bash salt '*' cisconso.info ''' return _proxy_cmd('info') def get_data(datastore, path): ''' Get the configuration of the device tree at the given path :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, / separated :type path: ``list``, ``str`` OR ``tuple`` :return: The network configuration at that tree :rtype: ``dict`` .. code-block:: bash salt cisco-nso cisconso.get_data running 'devices/ex0' ''' if isinstance(path, six.string_types): path = '/'.split(path) return _proxy_cmd('get_data', datastore, path) def get_rollbacks(): ''' Get a list of stored configuration rollbacks .. code-block:: bash salt cisco-nso cisconso.get_rollbacks ''' return _proxy_cmd('get_rollbacks') def get_rollback(name): ''' Get the backup of stored a configuration rollback :param name: Typically an ID of the backup :type name: ``str`` :rtype: ``str`` :return: the contents of the rollback snapshot .. code-block:: bash salt cisco-nso cisconso.get_rollback 52 ''' return _proxy_cmd('get_rollback', name) def apply_rollback(datastore, name): ''' Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` .. code-block:: bash salt cisco-nso cisconso.apply_rollback 52 ''' return _proxy_cmd('apply_rollback', datastore, name) def _proxy_cmd(command, *args, **kwargs): ''' run commands from __proxy__ :mod:`salt.proxy.cisconso<salt.proxy.cisconso>` command function from `salt.proxy.cisconso` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function ''' proxy_prefix = __opts__['proxy']['proxytype'] proxy_cmd = '.'.join([proxy_prefix, command]) if proxy_cmd not in __proxy__: return False for k in kwargs: if k.startswith('__pub_'): kwargs.pop(k) return __proxy__[proxy_cmd](*args, **kwargs)
saltstack/salt
salt/states/postgres_initdb.py
present
python
def present(name, user=None, password=None, auth='password', encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Initialize the PostgreSQL data directory name The name of the directory to initialize user The database superuser name password The password to set for the postgres user auth The default authentication method for local connections encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' _cmt = 'Postgres data directory {0} is already present'.format(name) ret = { 'name': name, 'changes': {}, 'result': True, 'comment': _cmt} if not __salt__['postgres.datadir_exists'](name=name): if __opts__['test']: ret['result'] = None _cmt = 'Postgres data directory {0} is set to be initialized'\ .format(name) ret['comment'] = _cmt return ret kwargs = dict( user=user, password=password, auth=auth, encoding=encoding, locale=locale, waldir=waldir, checksums=checksums, runas=runas) if __salt__['postgres.datadir_init'](name, **kwargs): _cmt = 'Postgres data directory {0} has been initialized'\ .format(name) ret['comment'] = _cmt ret['changes'][name] = 'Present' else: _cmt = 'Postgres data directory {0} initialization failed'\ .format(name) ret['result'] = False ret['comment'] = _cmt return ret
Initialize the PostgreSQL data directory name The name of the directory to initialize user The database superuser name password The password to set for the postgres user auth The default authentication method for local connections encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_initdb.py#L39-L121
null
# -*- coding: utf-8 -*- ''' Initialization of PostgreSQL data directory =========================================== The postgres_initdb module is used to initialize the postgresql data directory. .. versionadded:: 2016.3.0 .. code-block:: yaml pgsql-data-dir: postgres_initdb.present: - name: /var/lib/pgsql/data - auth: password - user: postgres - password: strong_password - encoding: UTF8 - locale: C - runas: postgres - allow_group_access: True - data_checksums: True - wal_segsize: 32 ''' from __future__ import absolute_import, unicode_literals, print_function def __virtual__(): ''' Only load if the postgres module is present ''' if 'postgres.datadir_init' not in __salt__: return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.') return True
saltstack/salt
salt/modules/wordpress.py
list_plugins
python
def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp = __salt__['cmd.shell'](( 'wp --path={0} plugin list' ).format(path), runas=user) for line in resp.split('\n')[1:]: ret.append(line.split('\t')) return [plugin.__dict__ for plugin in map(_get_plugins, ret)]
List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L29-L51
null
# -*- coding: utf-8 -*- ''' This module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python Modules from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino') def __virtual__(): if salt.utils.path.which('wp'): return True return False def _get_plugins(stuff): return Plugin(stuff) def show_plugin(name, path, user): ''' Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache ''' ret = {'name': name} resp = __salt__['cmd.shell'](( 'wp --path={0} plugin status {1}' ).format(path, name), runas=user).split('\n') for line in resp: if 'Status' in line: ret['status'] = line.split(' ')[-1].lower() elif 'Version' in line: ret['version'] = line.split(' ')[-1].lower() return ret def activate(name, path, user): ''' Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'active': # already active return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin activate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'active': return True return False def deactivate(name, path, user): ''' Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'inactive': # already inactive return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin deactivate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'inactive': return True return False def is_installed(path, user=None): ''' Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core is-installed' ).format(path), runas=user) if retcode == 0: return True return False def install(path, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core install ' '--title="{1}" ' '--admin_user={2} ' "--admin_password='{3}' " '--admin_email={4} ' '--url={5}' ).format( path, title, admin_user, admin_password, admin_email, url ), runas=user) if retcode == 0: return True return False
saltstack/salt
salt/modules/wordpress.py
show_plugin
python
def show_plugin(name, path, user): ''' Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache ''' ret = {'name': name} resp = __salt__['cmd.shell'](( 'wp --path={0} plugin status {1}' ).format(path, name), runas=user).split('\n') for line in resp: if 'Status' in line: ret['status'] = line.split(' ')[-1].lower() elif 'Version' in line: ret['version'] = line.split(' ')[-1].lower() return ret
Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L54-L82
null
# -*- coding: utf-8 -*- ''' This module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python Modules from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino') def __virtual__(): if salt.utils.path.which('wp'): return True return False def _get_plugins(stuff): return Plugin(stuff) def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp = __salt__['cmd.shell'](( 'wp --path={0} plugin list' ).format(path), runas=user) for line in resp.split('\n')[1:]: ret.append(line.split('\t')) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] def activate(name, path, user): ''' Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'active': # already active return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin activate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'active': return True return False def deactivate(name, path, user): ''' Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'inactive': # already inactive return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin deactivate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'inactive': return True return False def is_installed(path, user=None): ''' Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core is-installed' ).format(path), runas=user) if retcode == 0: return True return False def install(path, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core install ' '--title="{1}" ' '--admin_user={2} ' "--admin_password='{3}' " '--admin_email={4} ' '--url={5}' ).format( path, title, admin_user, admin_password, admin_email, url ), runas=user) if retcode == 0: return True return False
saltstack/salt
salt/modules/wordpress.py
activate
python
def activate(name, path, user): ''' Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'active': # already active return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin activate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'active': return True return False
Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L85-L115
[ "def show_plugin(name, path, user):\n '''\n Show a plugin in a wordpress install and check if it is installed\n\n name\n Wordpress plugin name\n\n path\n path to wordpress install location\n\n user\n user to run the command as\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' wordpress.show_plugin HyperDB /var/www/html apache\n '''\n ret = {'name': name}\n resp = __salt__['cmd.shell']((\n 'wp --path={0} plugin status {1}'\n ).format(path, name), runas=user).split('\\n')\n for line in resp:\n if 'Status' in line:\n ret['status'] = line.split(' ')[-1].lower()\n elif 'Version' in line:\n ret['version'] = line.split(' ')[-1].lower()\n return ret\n" ]
# -*- coding: utf-8 -*- ''' This module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python Modules from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino') def __virtual__(): if salt.utils.path.which('wp'): return True return False def _get_plugins(stuff): return Plugin(stuff) def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp = __salt__['cmd.shell'](( 'wp --path={0} plugin list' ).format(path), runas=user) for line in resp.split('\n')[1:]: ret.append(line.split('\t')) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] def show_plugin(name, path, user): ''' Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache ''' ret = {'name': name} resp = __salt__['cmd.shell'](( 'wp --path={0} plugin status {1}' ).format(path, name), runas=user).split('\n') for line in resp: if 'Status' in line: ret['status'] = line.split(' ')[-1].lower() elif 'Version' in line: ret['version'] = line.split(' ')[-1].lower() return ret def deactivate(name, path, user): ''' Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'inactive': # already inactive return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin deactivate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'inactive': return True return False def is_installed(path, user=None): ''' Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core is-installed' ).format(path), runas=user) if retcode == 0: return True return False def install(path, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core install ' '--title="{1}" ' '--admin_user={2} ' "--admin_password='{3}' " '--admin_email={4} ' '--url={5}' ).format( path, title, admin_user, admin_password, admin_email, url ), runas=user) if retcode == 0: return True return False
saltstack/salt
salt/modules/wordpress.py
is_installed
python
def is_installed(path, user=None): ''' Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core is-installed' ).format(path), runas=user) if retcode == 0: return True return False
Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L151-L172
null
# -*- coding: utf-8 -*- ''' This module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python Modules from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino') def __virtual__(): if salt.utils.path.which('wp'): return True return False def _get_plugins(stuff): return Plugin(stuff) def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp = __salt__['cmd.shell'](( 'wp --path={0} plugin list' ).format(path), runas=user) for line in resp.split('\n')[1:]: ret.append(line.split('\t')) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] def show_plugin(name, path, user): ''' Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache ''' ret = {'name': name} resp = __salt__['cmd.shell'](( 'wp --path={0} plugin status {1}' ).format(path, name), runas=user).split('\n') for line in resp: if 'Status' in line: ret['status'] = line.split(' ')[-1].lower() elif 'Version' in line: ret['version'] = line.split(' ')[-1].lower() return ret def activate(name, path, user): ''' Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'active': # already active return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin activate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'active': return True return False def deactivate(name, path, user): ''' Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'inactive': # already inactive return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin deactivate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'inactive': return True return False def install(path, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core install ' '--title="{1}" ' '--admin_user={2} ' "--admin_password='{3}' " '--admin_email={4} ' '--url={5}' ).format( path, title, admin_user, admin_password, admin_email, url ), runas=user) if retcode == 0: return True return False
saltstack/salt
salt/modules/wordpress.py
install
python
def install(path, user, admin_user, admin_password, admin_email, title, url): ''' Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core install ' '--title="{1}" ' '--admin_user={2} ' "--admin_password='{3}' " '--admin_email={4} ' '--url={5}' ).format( path, title, admin_user, admin_password, admin_email, url ), runas=user) if retcode == 0: return True return False
Run the initial setup functions for a wordpress install path path to wordpress install location user user to run the command as admin_user Username for the Administrative user for the wordpress install admin_password Initial Password for the Administrative user for the wordpress install admin_email Email for the Administrative user for the wordpress install title Title of the wordpress website for the wordpress install url Url for the wordpress install CLI Example: .. code-block:: bash salt '*' wordpress.install /var/www/html apache dwallace password123 \ dwallace@example.com "Daniel's Awesome Blog" https://blog.dwallace.com
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L175-L225
null
# -*- coding: utf-8 -*- ''' This module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ ''' # Import Python Modules from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino') def __virtual__(): if salt.utils.path.which('wp'): return True return False def _get_plugins(stuff): return Plugin(stuff) def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp = __salt__['cmd.shell'](( 'wp --path={0} plugin list' ).format(path), runas=user) for line in resp.split('\n')[1:]: ret.append(line.split('\t')) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] def show_plugin(name, path, user): ''' Show a plugin in a wordpress install and check if it is installed name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.show_plugin HyperDB /var/www/html apache ''' ret = {'name': name} resp = __salt__['cmd.shell'](( 'wp --path={0} plugin status {1}' ).format(path, name), runas=user).split('\n') for line in resp: if 'Status' in line: ret['status'] = line.split(' ')[-1].lower() elif 'Version' in line: ret['version'] = line.split(' ')[-1].lower() return ret def activate(name, path, user): ''' Activate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.activate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'active': # already active return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin activate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'active': return True return False def deactivate(name, path, user): ''' Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html apache ''' check = show_plugin(name, path, user) if check['status'] == 'inactive': # already inactive return None resp = __salt__['cmd.shell'](( 'wp --path={0} plugin deactivate {1}' ).format(path, name), runas=user) if 'Success' in resp: return True elif show_plugin(name, path, user)['status'] == 'inactive': return True return False def is_installed(path, user=None): ''' Check if wordpress is installed and setup path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.is_installed /var/www/html apache ''' retcode = __salt__['cmd.retcode'](( 'wp --path={0} core is-installed' ).format(path), runas=user) if retcode == 0: return True return False
saltstack/salt
salt/matchers/grain_pcre_match.py
match
python
def match(tgt, delimiter=DEFAULT_TARGET_DELIM, opts=None): ''' Matches a grain based on regex ''' if not opts: opts = __opts__ log.debug('grains pcre target: %s', tgt) if delimiter not in tgt: log.error('Got insufficient arguments for grains pcre match ' 'statement from master') return False return salt.utils.data.subdict_match( opts['grains'], tgt, delimiter=delimiter, regex_match=True)
Matches a grain based on regex
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/grain_pcre_match.py#L15-L28
[ "def subdict_match(data,\n expr,\n delimiter=DEFAULT_TARGET_DELIM,\n regex_match=False,\n exact_match=False):\n '''\n Check for a match in a dictionary using a delimiter character to denote\n levels of subdicts, and also allowing the delimiter character to be\n matched. Thus, 'foo:bar:baz' will match data['foo'] == 'bar:baz' and\n data['foo']['bar'] == 'baz'. The latter would take priority over the\n former, as more deeply-nested matches are tried first.\n '''\n def _match(target, pattern, regex_match=False, exact_match=False):\n # The reason for using six.text_type first and _then_ using\n # to_unicode as a fallback is because we want to eventually have\n # unicode types for comparison below. If either value is numeric then\n # six.text_type will turn it into a unicode string. However, if the\n # value is a PY2 str type with non-ascii chars, then the result will be\n # a UnicodeDecodeError. In those cases, we simply use to_unicode to\n # decode it to unicode. The reason we can't simply use to_unicode to\n # begin with is that (by design) to_unicode will raise a TypeError if a\n # non-string/bytestring/bytearray value is passed.\n try:\n target = six.text_type(target).lower()\n except UnicodeDecodeError:\n target = salt.utils.stringutils.to_unicode(target).lower()\n try:\n pattern = six.text_type(pattern).lower()\n except UnicodeDecodeError:\n pattern = salt.utils.stringutils.to_unicode(pattern).lower()\n\n if regex_match:\n try:\n return re.match(pattern, target)\n except Exception:\n log.error('Invalid regex \\'%s\\' in match', pattern)\n return False\n else:\n return target == pattern if exact_match \\\n else fnmatch.fnmatch(target, pattern)\n\n def _dict_match(target, pattern, regex_match=False, exact_match=False):\n wildcard = pattern.startswith('*:')\n if wildcard:\n pattern = pattern[2:]\n\n if pattern == '*':\n # We are just checking that the key exists\n return True\n elif pattern in target:\n # We might want to search for a key\n return True\n elif subdict_match(target,\n pattern,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n if wildcard:\n for key in target:\n if isinstance(target[key], dict):\n if _dict_match(target[key],\n pattern,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n elif isinstance(target[key], list):\n for item in target[key]:\n if _match(item,\n pattern,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n elif _match(target[key],\n pattern,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n return False\n\n splits = expr.split(delimiter)\n num_splits = len(splits)\n if num_splits == 1:\n # Delimiter not present, this can't possibly be a match\n return False\n\n splits = expr.split(delimiter)\n num_splits = len(splits)\n if num_splits == 1:\n # Delimiter not present, this can't possibly be a match\n return False\n\n # If we have 4 splits, then we have three delimiters. Thus, the indexes we\n # want to use are 3, 2, and 1, in that order.\n for idx in range(num_splits - 1, 0, -1):\n key = delimiter.join(splits[:idx])\n if key == '*':\n # We are matching on everything under the top level, so we need to\n # treat the match as the entire data being passed in\n matchstr = expr\n match = data\n else:\n matchstr = delimiter.join(splits[idx:])\n match = traverse_dict_and_list(data, key, {}, delimiter=delimiter)\n log.debug(\"Attempting to match '%s' in '%s' using delimiter '%s'\",\n matchstr, key, delimiter)\n if match == {}:\n continue\n if isinstance(match, dict):\n if _dict_match(match,\n matchstr,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n continue\n if isinstance(match, (list, tuple)):\n # We are matching a single component to a single list member\n for member in match:\n if isinstance(member, dict):\n if _dict_match(member,\n matchstr,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n if _match(member,\n matchstr,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n continue\n if _match(match,\n matchstr,\n regex_match=regex_match,\n exact_match=exact_match):\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' This is the default grains PCRE matcher. ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.defaults import DEFAULT_TARGET_DELIM # pylint: disable=3rd-party-module-not-gated import salt.utils.data # pylint: disable=3rd-party-module-not-gated log = logging.getLogger(__name__)
saltstack/salt
salt/utils/yamldumper.py
dump
python
def dump(data, stream=None, **kwargs): ''' .. versionadded:: 2018.3.0 Helper that wraps yaml.dump and ensures that we encode unicode strings unless explicitly told not to. ''' if 'allow_unicode' not in kwargs: kwargs['allow_unicode'] = True return yaml.dump(data, stream, **kwargs)
.. versionadded:: 2018.3.0 Helper that wraps yaml.dump and ensures that we encode unicode strings unless explicitly told not to.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamldumper.py#L116-L125
null
# -*- coding: utf-8 -*- ''' salt.utils.yamldumper ~~~~~~~~~~~~~~~~~~~~~ ''' # pylint: disable=W0232 # class has no __init__ method from __future__ import absolute_import, print_function, unicode_literals try: from yaml import CDumper as Dumper from yaml import CSafeDumper as SafeDumper except ImportError: from yaml import Dumper from yaml import SafeDumper import yaml # pylint: disable=blacklisted-import import collections import salt.utils.context import salt.utils.thread_local_proxy from salt.utils.odict import OrderedDict __all__ = ['OrderedDumper', 'SafeOrderedDumper', 'IndentedSafeOrderedDumper', 'get_dumper', 'dump', 'safe_dump'] class IndentMixin(Dumper): ''' Mixin that improves YAML dumped list readability by indenting them by two spaces, instead of being flush with the key they are under. ''' def increase_indent(self, flow=False, indentless=False): return super(IndentMixin, self).increase_indent(flow, False) class OrderedDumper(Dumper): ''' A YAML dumper that represents python OrderedDict as simple YAML map. ''' class SafeOrderedDumper(SafeDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map. ''' class IndentedSafeOrderedDumper(IndentMixin, SafeOrderedDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map, and also indents lists by two spaces. ''' pass def represent_ordereddict(dumper, data): return dumper.represent_dict(list(data.items())) OrderedDumper.add_representer(OrderedDict, represent_ordereddict) SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict) OrderedDumper.add_representer( collections.defaultdict, yaml.representer.SafeRepresenter.represent_dict ) SafeOrderedDumper.add_representer( collections.defaultdict, yaml.representer.SafeRepresenter.represent_dict ) OrderedDumper.add_representer( salt.utils.context.NamespacedDictWrapper, yaml.representer.SafeRepresenter.represent_dict ) SafeOrderedDumper.add_representer( salt.utils.context.NamespacedDictWrapper, yaml.representer.SafeRepresenter.represent_dict ) OrderedDumper.add_representer( 'tag:yaml.org,2002:timestamp', OrderedDumper.represent_scalar) SafeOrderedDumper.add_representer( 'tag:yaml.org,2002:timestamp', SafeOrderedDumper.represent_scalar) # DO NOT MOVE THIS FUNCTION! It must be defined after the representers above # have been added, so that it has access to the manually-added representers # above when it looks for a representer for the proxy object's __class__. def represent_thread_local_proxy(dumper, data): if data.__class__ in dumper.yaml_representers: return dumper.yaml_representers[data.__class__](dumper, data) return dumper.represent_undefined(data) OrderedDumper.add_representer( salt.utils.thread_local_proxy.ThreadLocalProxy, represent_thread_local_proxy) SafeOrderedDumper.add_representer( salt.utils.thread_local_proxy.ThreadLocalProxy, represent_thread_local_proxy) def get_dumper(dumper_name): return { 'OrderedDumper': OrderedDumper, 'SafeOrderedDumper': SafeOrderedDumper, 'IndentedSafeOrderedDumper': IndentedSafeOrderedDumper, }.get(dumper_name) def safe_dump(data, stream=None, **kwargs): ''' Use a custom dumper to ensure that defaultdict and OrderedDict are represented properly. Ensure that unicode strings are encoded unless explicitly told not to. ''' if 'allow_unicode' not in kwargs: kwargs['allow_unicode'] = True return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)
saltstack/salt
salt/utils/yamldumper.py
safe_dump
python
def safe_dump(data, stream=None, **kwargs): ''' Use a custom dumper to ensure that defaultdict and OrderedDict are represented properly. Ensure that unicode strings are encoded unless explicitly told not to. ''' if 'allow_unicode' not in kwargs: kwargs['allow_unicode'] = True return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)
Use a custom dumper to ensure that defaultdict and OrderedDict are represented properly. Ensure that unicode strings are encoded unless explicitly told not to.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamldumper.py#L128-L136
null
# -*- coding: utf-8 -*- ''' salt.utils.yamldumper ~~~~~~~~~~~~~~~~~~~~~ ''' # pylint: disable=W0232 # class has no __init__ method from __future__ import absolute_import, print_function, unicode_literals try: from yaml import CDumper as Dumper from yaml import CSafeDumper as SafeDumper except ImportError: from yaml import Dumper from yaml import SafeDumper import yaml # pylint: disable=blacklisted-import import collections import salt.utils.context import salt.utils.thread_local_proxy from salt.utils.odict import OrderedDict __all__ = ['OrderedDumper', 'SafeOrderedDumper', 'IndentedSafeOrderedDumper', 'get_dumper', 'dump', 'safe_dump'] class IndentMixin(Dumper): ''' Mixin that improves YAML dumped list readability by indenting them by two spaces, instead of being flush with the key they are under. ''' def increase_indent(self, flow=False, indentless=False): return super(IndentMixin, self).increase_indent(flow, False) class OrderedDumper(Dumper): ''' A YAML dumper that represents python OrderedDict as simple YAML map. ''' class SafeOrderedDumper(SafeDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map. ''' class IndentedSafeOrderedDumper(IndentMixin, SafeOrderedDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map, and also indents lists by two spaces. ''' pass def represent_ordereddict(dumper, data): return dumper.represent_dict(list(data.items())) OrderedDumper.add_representer(OrderedDict, represent_ordereddict) SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict) OrderedDumper.add_representer( collections.defaultdict, yaml.representer.SafeRepresenter.represent_dict ) SafeOrderedDumper.add_representer( collections.defaultdict, yaml.representer.SafeRepresenter.represent_dict ) OrderedDumper.add_representer( salt.utils.context.NamespacedDictWrapper, yaml.representer.SafeRepresenter.represent_dict ) SafeOrderedDumper.add_representer( salt.utils.context.NamespacedDictWrapper, yaml.representer.SafeRepresenter.represent_dict ) OrderedDumper.add_representer( 'tag:yaml.org,2002:timestamp', OrderedDumper.represent_scalar) SafeOrderedDumper.add_representer( 'tag:yaml.org,2002:timestamp', SafeOrderedDumper.represent_scalar) # DO NOT MOVE THIS FUNCTION! It must be defined after the representers above # have been added, so that it has access to the manually-added representers # above when it looks for a representer for the proxy object's __class__. def represent_thread_local_proxy(dumper, data): if data.__class__ in dumper.yaml_representers: return dumper.yaml_representers[data.__class__](dumper, data) return dumper.represent_undefined(data) OrderedDumper.add_representer( salt.utils.thread_local_proxy.ThreadLocalProxy, represent_thread_local_proxy) SafeOrderedDumper.add_representer( salt.utils.thread_local_proxy.ThreadLocalProxy, represent_thread_local_proxy) def get_dumper(dumper_name): return { 'OrderedDumper': OrderedDumper, 'SafeOrderedDumper': SafeOrderedDumper, 'IndentedSafeOrderedDumper': IndentedSafeOrderedDumper, }.get(dumper_name) def dump(data, stream=None, **kwargs): ''' .. versionadded:: 2018.3.0 Helper that wraps yaml.dump and ensures that we encode unicode strings unless explicitly told not to. ''' if 'allow_unicode' not in kwargs: kwargs['allow_unicode'] = True return yaml.dump(data, stream, **kwargs)
saltstack/salt
salt/cloud/clouds/opennebula.py
avail_images
python
def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images
Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L132-L160
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
avail_locations
python
def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations
Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L163-L190
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
list_clusters
python
def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters
Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L212-L237
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
list_datastores
python
def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores
Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L240-L265
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
list_security_groups
python
def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups
Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L346-L371
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
list_templates
python
def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates
Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L374-L399
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
list_vns
python
def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns
Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L402-L427
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
reboot
python
def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call)
Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L430-L452
[ "def vm_action(name, kwargs=None, call=None):\n '''\n Submits an action to be performed on a given virtual machine.\n\n .. versionadded:: 2016.3.0\n\n name\n The name of the VM to action.\n\n action\n The action to be performed on the VM. Available options include:\n - boot\n - delete\n - delete-recreate\n - hold\n - poweroff\n - poweroff-hard\n - reboot\n - reboot-hard\n - release\n - resched\n - resume\n - shutdown\n - shutdown-hard\n - stop\n - suspend\n - undeploy\n - undeploy-hard\n - unresched\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a vm_action my-vm action='release'\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The vm_action function must be called with -a or --action.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n action = kwargs.get('action', None)\n if action is None:\n raise SaltCloudSystemExit(\n 'The vm_action function must have an \\'action\\' provided.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n vm_id = int(get_vm_id(kwargs={'name': name}))\n response = server.one.vm.action(auth, action, vm_id)\n\n data = {\n 'action': 'vm.action.' + six.text_type(action),\n 'actioned': response[0],\n 'vm_id': response[1],\n 'error_code': response[2],\n }\n\n return data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
start
python
def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call)
Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L455-L477
[ "def vm_action(name, kwargs=None, call=None):\n '''\n Submits an action to be performed on a given virtual machine.\n\n .. versionadded:: 2016.3.0\n\n name\n The name of the VM to action.\n\n action\n The action to be performed on the VM. Available options include:\n - boot\n - delete\n - delete-recreate\n - hold\n - poweroff\n - poweroff-hard\n - reboot\n - reboot-hard\n - release\n - resched\n - resume\n - shutdown\n - shutdown-hard\n - stop\n - suspend\n - undeploy\n - undeploy-hard\n - unresched\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a vm_action my-vm action='release'\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The vm_action function must be called with -a or --action.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n action = kwargs.get('action', None)\n if action is None:\n raise SaltCloudSystemExit(\n 'The vm_action function must have an \\'action\\' provided.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n vm_id = int(get_vm_id(kwargs={'name': name}))\n response = server.one.vm.action(auth, action, vm_id)\n\n data = {\n 'action': 'vm.action.' + six.text_type(action),\n 'actioned': response[0],\n 'vm_id': response[1],\n 'error_code': response[2],\n }\n\n return data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
stop
python
def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call)
Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L480-L502
[ "def vm_action(name, kwargs=None, call=None):\n '''\n Submits an action to be performed on a given virtual machine.\n\n .. versionadded:: 2016.3.0\n\n name\n The name of the VM to action.\n\n action\n The action to be performed on the VM. Available options include:\n - boot\n - delete\n - delete-recreate\n - hold\n - poweroff\n - poweroff-hard\n - reboot\n - reboot-hard\n - release\n - resched\n - resume\n - shutdown\n - shutdown-hard\n - stop\n - suspend\n - undeploy\n - undeploy-hard\n - unresched\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a vm_action my-vm action='release'\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The vm_action function must be called with -a or --action.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n action = kwargs.get('action', None)\n if action is None:\n raise SaltCloudSystemExit(\n 'The vm_action function must have an \\'action\\' provided.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n vm_id = int(get_vm_id(kwargs={'name': name}))\n response = server.one.vm.action(auth, action, vm_id)\n\n data = {\n 'action': 'vm.action.' + six.text_type(action),\n 'actioned': response[0],\n 'vm_id': response[1],\n 'error_code': response[2],\n }\n\n return data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_one_version
python
def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1]
Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L505-L529
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_cluster_id
python
def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret
Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L532-L565
[ "def list_clusters(call=None):\n '''\n Returns a list of clusters in OpenNebula.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_clusters opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_clusters function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n cluster_pool = server.one.clusterpool.info(auth)[1]\n\n clusters = {}\n for cluster in _get_xml(cluster_pool):\n clusters[cluster.find('NAME').text] = _xml_to_dict(cluster)\n\n return clusters\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_datastore_id
python
def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret
Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L568-L601
[ "def list_datastores(call=None):\n '''\n Returns a list of data stores on OpenNebula.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_datastores opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_datastores function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n datastore_pool = server.one.datastorepool.info(auth)[1]\n\n datastores = {}\n for datastore in _get_xml(datastore_pool):\n datastores[datastore.find('NAME').text] = _xml_to_dict(datastore)\n\n return datastores\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_host_id
python
def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret
Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L604-L637
[ "def avail_locations(call=None):\n '''\n Return available OpenNebula locations.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-locations opennebula\n salt-cloud --function avail_locations opennebula\n salt-cloud -f avail_locations opennebula\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_locations function must be called with '\n '-f or --function, or with the --list-locations option.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n host_pool = server.one.hostpool.info(auth)[1]\n\n locations = {}\n for host in _get_xml(host_pool):\n locations[host.find('NAME').text] = _xml_to_dict(host)\n\n return locations\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_image
python
def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) )
r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L640-L656
[ "def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n", "def avail_images(call=None):\n '''\n Return available OpenNebula images.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-images opennebula\n salt-cloud --function avail_images opennebula\n salt-cloud -f avail_images opennebula\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n\n image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1]\n\n images = {}\n for image in _get_xml(image_pool):\n images[image.find('NAME').text] = _xml_to_dict(image)\n\n return images\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_image_id
python
def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret
Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L659-L692
[ "def avail_images(call=None):\n '''\n Return available OpenNebula images.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-images opennebula\n salt-cloud --function avail_images opennebula\n salt-cloud -f avail_images opennebula\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n\n image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1]\n\n images = {}\n for image in _get_xml(image_pool):\n images[image.find('NAME').text] = _xml_to_dict(image)\n\n return images\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_secgroup_id
python
def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret
Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L721-L754
[ "def list_security_groups(call=None):\n '''\n Lists all security groups available to the user and the user's groups.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_security_groups opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_security_groups function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1]\n\n groups = {}\n for group in _get_xml(secgroup_pool):\n groups[group.find('NAME').text] = _xml_to_dict(group)\n\n return groups\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_template_image
python
def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret
Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L757-L788
[ "def list_templates(call=None):\n '''\n Lists all templates available to the user and the user's groups.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_templates opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_templates function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1]\n\n templates = {}\n for template in _get_xml(template_pool):\n templates[template.find('NAME').text] = _xml_to_dict(template)\n\n return templates\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_template
python
def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) )
r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L827-L845
[ "def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n", "def list_templates(call=None):\n '''\n Lists all templates available to the user and the user's groups.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_templates opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_templates function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1]\n\n templates = {}\n for template in _get_xml(template_pool):\n templates[template.find('NAME').text] = _xml_to_dict(template)\n\n return templates\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_vm_id
python
def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret
Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L848-L881
[ "def list_nodes(call=None):\n '''\n Return a list of VMs on OpenNebula.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -Q\n salt-cloud --query\n salt-cloud --function list_nodes opennebula\n salt-cloud -f list_nodes opennebula\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes function must be called with -f or --function.'\n )\n\n return _list_nodes(full=False)\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
get_vn_id
python
def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret
Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L884-L917
[ "def list_vns(call=None):\n '''\n Lists all virtual networks available to the user and the user's groups.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_vns opennebula\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_vns function must be called with -f or --function.'\n )\n\n server, user, password = _get_xml_rpc()\n auth = ':'.join([user, password])\n vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1]\n\n vns = {}\n for v_network in _get_xml(vn_pool):\n vns[v_network.find('NAME').text] = _xml_to_dict(v_network)\n\n return vns\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
_get_device_template
python
def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp
Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L920-L963
null
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
create
python
def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret
r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L967-L1178
[ "def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n", "def get_template(vm_):\n r'''\n Return the template id for a VM.\n\n .. versionadded:: 2016.11.0\n\n vm\\_\n The VM dictionary for which to obtain a template.\n '''\n\n vm_template = six.text_type(config.get_cloud_config_value(\n 'template', vm_, __opts__, search_global=False\n ))\n try:\n return list_templates()[vm_template]['id']\n except KeyError:\n raise SaltCloudNotFound(\n 'The specified template, \\'{0}\\', could not be found.'.format(vm_template)\n )\n", "def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n", "def get_location(vm_):\n r'''\n Return the VM's location.\n\n vm\\_\n The VM dictionary for which to obtain a location.\n '''\n locations = avail_locations()\n vm_location = six.text_type(config.get_cloud_config_value(\n 'location', vm_, __opts__, search_global=False\n ))\n\n if vm_location == 'None':\n return None\n\n for location in locations:\n if vm_location in (locations[location]['name'],\n locations[location]['id']):\n return locations[location]['id']\n raise SaltCloudNotFound(\n 'The specified location, \\'{0}\\', could not be found.'.format(\n vm_location\n )\n )\n", "def get_template_id(kwargs=None, call=None):\n '''\n Returns a template's ID from the given template name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_template_id opennebula name=my-template-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_template_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_template_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_templates()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The template \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
destroy
python
def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data
Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1181-L1240
[ "def show_instance(name, call=None):\n '''\n Show the details from OpenNebula concerning a named VM.\n\n name\n The name of the VM for which to display details.\n\n call\n Type of call to use with this function such as ``function``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --action show_instance vm_name\n salt-cloud -a show_instance vm_name\n\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n\n node = _get_node(name)\n __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)\n\n return node\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_allocate
python
def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret
Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1243-L1328
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_datastore_id(kwargs=None, call=None):\n '''\n Returns a data store's ID from the given data store name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_datastore_id opennebula name=my-datastore-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_datastore_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_datastore_id function requires a name.'\n )\n\n try:\n ret = list_datastores()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The datastore \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_clone
python
def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data
Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1331-L1396
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_image_id(kwargs=None, call=None):\n '''\n Returns an image's ID from the given image name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_image_id opennebula name=my-image-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_image_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_image_id function requires a name.'\n )\n\n try:\n ret = avail_images()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The image \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_info
python
def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info
Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1458-L1513
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n", "def get_image_id(kwargs=None, call=None):\n '''\n Returns an image's ID from the given image name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_image_id opennebula name=my-image-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_image_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_image_id function requires a name.'\n )\n\n try:\n ret = avail_images()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The image \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_persistent
python
def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data
Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1516-L1582
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_image_id(kwargs=None, call=None):\n '''\n Returns an image's ID from the given image name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_image_id opennebula name=my-image-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_image_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_image_id function requires a name.'\n )\n\n try:\n ret = avail_images()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The image \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_snapshot_delete
python
def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data
Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1585-L1651
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_image_id(kwargs=None, call=None):\n '''\n Returns an image's ID from the given image name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_image_id opennebula name=my-image-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_image_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_image_id function requires a name.'\n )\n\n try:\n ret = avail_images()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The image \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
image_update
python
def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret
Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L1789-L1894
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_image_id(kwargs=None, call=None):\n '''\n Returns an image's ID from the given image name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_image_id opennebula name=my-image-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_image_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_image_id function requires a name.'\n )\n\n try:\n ret = avail_images()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The image \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
secgroup_delete
python
def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data
Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2060-L2117
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_secgroup_id(kwargs=None, call=None):\n '''\n Returns a security group's ID from the given security group name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_security_groups()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The security group \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
secgroup_info
python
def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info
Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2120-L2175
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n", "def get_secgroup_id(kwargs=None, call=None):\n '''\n Returns a security group's ID from the given security group name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_security_groups()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The security group \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
secgroup_update
python
def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret
Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2178-L2287
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_secgroup_id(kwargs=None, call=None):\n '''\n Returns a security group's ID from the given security group name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_secgroup_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_security_groups()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The security group \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
template_allocate
python
def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret
Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2290-L2353
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
template_clone
python
def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data
Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2356-L2426
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_template_id(kwargs=None, call=None):\n '''\n Returns a template's ID from the given template name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_template_id opennebula name=my-template-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_template_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_template_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_templates()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The template \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
template_delete
python
def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data
Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2429-L2485
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_template_id(kwargs=None, call=None):\n '''\n Returns a template's ID from the given template name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_template_id opennebula name=my-template-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_template_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_template_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_templates()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The template \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
template_instantiate
python
def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data
Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2488-L2560
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_template_id(kwargs=None, call=None):\n '''\n Returns a template's ID from the given template name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_template_id opennebula name=my-template-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_template_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_template_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_templates()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The template \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
template_update
python
def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret
Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2563-L2672
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_template_id(kwargs=None, call=None):\n '''\n Returns a template's ID from the given template name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_template_id opennebula name=my-template-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_template_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_template_id function requires a \\'name\\'.'\n )\n\n try:\n ret = list_templates()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The template \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_action
python
def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2675-L2737
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_allocate
python
def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret
Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2740-L2805
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_attach
python
def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret
Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2808-L2872
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_deploy
python
def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2942-L3038
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_datastore_id(kwargs=None, call=None):\n '''\n Returns a data store's ID from the given data store name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_datastore_id opennebula name=my-datastore-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_datastore_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_datastore_id function requires a name.'\n )\n\n try:\n ret = list_datastores()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The datastore \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n", "def get_host_id(kwargs=None, call=None):\n '''\n Returns a host's ID from the given host name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_host_id opennebula name=my-host-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_host_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_host_id function requires a name.'\n )\n\n try:\n ret = avail_locations()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The host \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_detach
python
def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3041-L3085
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_detach_nic
python
def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3088-L3132
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_disk_save
python
def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data
Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3135-L3202
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_disk_snapshot_create
python
def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data
Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3205-L3258
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_disk_snapshot_delete
python
def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data
Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3261-L3314
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_info
python
def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info
Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3373-L3404
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_monitoring
python
def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info
Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3511-L3551
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_snapshot_create
python
def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data
Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3629-L3673
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_snapshot_delete
python
def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data
Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3676-L3720
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vm_update
python
def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret
Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3770-L3854
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vm_id(kwargs=None, call=None):\n '''\n Returns a virtual machine's ID from the given virtual machine's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vm_id opennebula name=my-vm\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vm_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vm_id function requires a name.'\n )\n\n try:\n ret = list_nodes()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VM \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vn_allocate
python
def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret
Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L3944-L4025
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_cluster_id(kwargs=None, call=None):\n '''\n Returns a cluster's ID from the given cluster name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_cluster_id opennebula name=my-cluster-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_cluster_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_cluster_id function requires a name.'\n )\n\n try:\n ret = list_clusters()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The cluster \\'{0}\\' could not be found'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vn_delete
python
def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data
Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4028-L4084
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vn_id(kwargs=None, call=None):\n '''\n Returns a virtual network's ID from the given virtual network's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vn_id opennebula name=my-vn-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vn_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vn_id function requires a name.'\n )\n\n try:\n ret = list_vns()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VN \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vn_free_ar
python
def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data
Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4087-L4153
[ "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vn_id(kwargs=None, call=None):\n '''\n Returns a virtual network's ID from the given virtual network's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vn_id opennebula name=my-vn-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vn_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vn_id function requires a name.'\n )\n\n try:\n ret = list_vns()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VN \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vn_info
python
def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info
Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4242-L4298
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n", "def get_vn_id(kwargs=None, call=None):\n '''\n Returns a virtual network's ID from the given virtual network's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vn_id opennebula name=my-vn-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vn_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vn_id function requires a name.'\n )\n\n try:\n ret = list_vns()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VN \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
vn_release
python
def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret
Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4301-L4384
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def get_vn_id(kwargs=None, call=None):\n '''\n Returns a virtual network's ID from the given virtual network's name.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f get_vn_id opennebula name=my-vn-name\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The get_vn_id function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n name = kwargs.get('name', None)\n if name is None:\n raise SaltCloudSystemExit(\n 'The get_vn_id function requires a name.'\n )\n\n try:\n ret = list_vns()[name]['id']\n except KeyError:\n raise SaltCloudSystemExit(\n 'The VN \\'{0}\\' could not be found.'.format(name)\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
_get_xml
python
def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data
Intrepret the data coming from opennebula and raise if it's not XML.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4500-L4512
null
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
_get_xml_rpc
python
def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password
Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4515-L4539
[ "def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n", "def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('xml_rpc', 'user', 'password')\n )\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
_list_nodes
python
def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms
Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4542-L4583
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n", "def _get_xml_rpc():\n '''\n Uses the OpenNebula cloud provider configurations to connect to the\n OpenNebula API.\n\n Returns the server connection created as well as the user and password\n values from the cloud provider config file used to make the connection.\n '''\n vm_ = get_configured_provider()\n\n xml_rpc = config.get_cloud_config_value(\n 'xml_rpc', vm_, __opts__, search_global=False\n )\n\n user = config.get_cloud_config_value(\n 'user', vm_, __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, search_global=False\n )\n\n server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n\n return server, user, password\n", "def _get_xml(xml_str):\n '''\n Intrepret the data coming from opennebula and raise if it's not XML.\n '''\n try:\n xml_data = etree.XML(xml_str)\n # XMLSyntaxError seems to be only available from lxml, but that is the xml\n # library loaded by this module\n except etree.XMLSyntaxError as err:\n # opennebula returned invalid XML, which could be an error message, so\n # log it\n raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str))\n return xml_data\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
saltstack/salt
salt/cloud/clouds/opennebula.py
_xml_to_dict
python
def _xml_to_dict(xml): ''' Helper function to covert xml into a data dictionary. xml The xml data to convert. ''' dicts = {} for item in xml: key = item.tag.lower() idx = 1 while key in dicts: key += six.text_type(idx) idx += 1 if item.text is None: dicts[key] = _xml_to_dict(item) else: dicts[key] = item.text return dicts
Helper function to covert xml into a data dictionary. xml The xml data to convert.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L4586-L4605
[ "def _xml_to_dict(xml):\n '''\n Helper function to covert xml into a data dictionary.\n\n xml\n The xml data to convert.\n '''\n dicts = {}\n for item in xml:\n key = item.tag.lower()\n idx = 1\n while key in dicts:\n key += six.text_type(idx)\n idx += 1\n if item.text is None:\n dicts[key] = _xml_to_dict(item)\n else:\n dicts[key] = item.text\n\n return dicts\n" ]
# -*- coding: utf-8 -*- ''' OpenNebula Cloud Module ======================= The OpenNebula cloud module is used to control access to an OpenNebula cloud. .. versionadded:: 2014.7.0 :depends: lxml :depends: OpenNebula installation running version ``4.14`` or later. Use of this module requires the ``xml_rpc``, ``user``, and ``password`` parameters to be set. Set up the cloud configuration at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/opennebula.conf``: .. code-block:: yaml my-opennebula-config: xml_rpc: http://localhost:2633/RPC2 user: oneadmin password: JHGhgsayu32jsa driver: opennebula This driver supports accessing new VM instances via DNS entry instead of IP address. To enable this feature, in the provider or profile file add `fqdn_base` with a value matching the base of your fully-qualified domain name. Example: .. code-block:: yaml my-opennebula-config: [...] fqdn_base: <my.basedomain.com> [...] The driver will prepend the hostname to the fqdn_base and do a DNS lookup to find the IP of the new VM. .. note: Whenever ``data`` is provided as a kwarg to a function and the attribute=value syntax is used, the entire ``data`` value must be wrapped in single or double quotes. If the value given in the attribute=value data string contains multiple words, double quotes *must* be used for the value while the entire data string should be encapsulated in single quotes. Failing to do so will result in an error. Example: .. code-block:: bash salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="My New Image" DESCRIPTION="Description of the image." \\ PATH=/home/one_user/images/image_name.img' salt-cloud -f secgroup_allocate opennebula \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import pprint import time # Import Salt Libs import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltCloudExecutionFailure, SaltCloudExecutionTimeout, SaltCloudNotFound, SaltCloudSystemExit ) import salt.utils.data import salt.utils.files # Import Third Party Libs from salt.ext import six try: import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 from lxml import etree HAS_XML_LIBS = True except ImportError: HAS_XML_LIBS = False # Get Logging Started log = logging.getLogger(__name__) __virtualname__ = 'opennebula' def __virtual__(): ''' Check for OpenNebula configs. ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('xml_rpc', 'user', 'password') ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'lmxl': HAS_XML_LIBS} ) def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1] images = {} for image in _get_xml(image_pool): images[image.find('NAME').text] = _xml_to_dict(image) return images def avail_locations(call=None): ''' Return available OpenNebula locations. CLI Example: .. code-block:: bash salt-cloud --list-locations opennebula salt-cloud --function avail_locations opennebula salt-cloud -f avail_locations opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) host_pool = server.one.hostpool.info(auth)[1] locations = {} for host in _get_xml(host_pool): locations[host.find('NAME').text] = _xml_to_dict(host) return locations def avail_sizes(call=None): ''' Because sizes are built into templates with OpenNebula, there will be no sizes to return here. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option.' ) log.warning( 'Because sizes are built into templates with OpenNebula, there are no sizes ' 'to return.' ) return {} def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cluster_pool = server.one.clusterpool.info(auth)[1] clusters = {} for cluster in _get_xml(cluster_pool): clusters[cluster.find('NAME').text] = _xml_to_dict(cluster) return clusters def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) datastore_pool = server.one.datastorepool.info(auth)[1] datastores = {} for datastore in _get_xml(datastore_pool): datastores[datastore.find('NAME').text] = _xml_to_dict(datastore) return datastores def list_hosts(call=None): ''' Returns a list of hosts on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_hosts opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosts function must be called with -f or --function.' ) return avail_locations() def list_nodes(call=None): ''' Return a list of VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud --function list_nodes opennebula salt-cloud -f list_nodes opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) return _list_nodes(full=False) def list_nodes_full(call=None): ''' Return a list of the VMs on OpenNebula. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud --function list_nodes_full opennebula salt-cloud -f list_nodes_full opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return _list_nodes(full=True) def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) return __utils__['cloud.list_nodes_select']( list_nodes_full('function'), __opts__['query.selection'], call, ) def list_security_groups(call=None): ''' Lists all security groups available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_security_groups opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_security_groups function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1] groups = {} for group in _get_xml(secgroup_pool): groups[group.find('NAME').text] = _xml_to_dict(group) return groups def list_templates(call=None): ''' Lists all templates available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_templates opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_templates function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) template_pool = server.one.templatepool.info(auth, -2, -1, -1)[1] templates = {} for template in _get_xml(template_pool): templates[template.find('NAME').text] = _xml_to_dict(template) return templates def list_vns(call=None): ''' Lists all virtual networks available to the user and the user's groups. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_vns opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_vns function must be called with -f or --function.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, -2, -1, -1)[1] vns = {} for v_network in _get_xml(vn_pool): vns[v_network.find('NAME').text] = _xml_to_dict(v_network) return vns def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Rebooting node %s', name) return vm_action(name, kwargs={'action': 'reboot'}, call=call) def start(name, call=None): ''' Start a VM. .. versionadded:: 2016.3.0 name The name of the VM to start. CLI Example: .. code-block:: bash salt-cloud -a start my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Starting node %s', name) return vm_action(name, kwargs={'action': 'resume'}, call=call) def stop(name, call=None): ''' Stop a VM. .. versionadded:: 2016.3.0 name The name of the VM to stop. CLI Example: .. code-block:: bash salt-cloud -a stop my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) log.info('Stopping node %s', name) return vm_action(name, kwargs={'action': 'stop'}, call=call) def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) return server.one.system.version(auth)[1] def get_cluster_id(kwargs=None, call=None): ''' Returns a cluster's ID from the given cluster name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_cluster_id opennebula name=my-cluster-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_cluster_id function requires a name.' ) try: ret = list_clusters()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The cluster \'{0}\' could not be found'.format(name) ) return ret def get_datastore_id(kwargs=None, call=None): ''' Returns a data store's ID from the given data store name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_datastore_id opennebula name=my-datastore-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_datastore_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_datastore_id function requires a name.' ) try: ret = list_datastores()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The datastore \'{0}\' could not be found.'.format(name) ) return ret def get_host_id(kwargs=None, call=None): ''' Returns a host's ID from the given host name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_host_id opennebula name=my-host-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_host_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_host_id function requires a name.' ) try: ret = avail_locations()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The host \'{0}\' could not be found'.format(name) ) return ret def get_image(vm_): r''' Return the image object to use. vm\_ The VM dictionary for which to obtain an image. ''' images = avail_images() vm_image = six.text_type(config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False )) for image in images: if vm_image in (images[image]['name'], images[image]['id']): return images[image]['id'] raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_image_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_image_id function requires a name.' ) try: ret = avail_images()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The image \'{0}\' could not be found'.format(name) ) return ret def get_location(vm_): r''' Return the VM's location. vm\_ The VM dictionary for which to obtain a location. ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) if vm_location == 'None': return None for location in locations: if vm_location in (locations[location]['name'], locations[location]['id']): return locations[location]['id'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def get_secgroup_id(kwargs=None, call=None): ''' Returns a security group's ID from the given security group name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_secgroup_id opennebula name=my-secgroup-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_secgroup_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_secgroup_id function requires a \'name\'.' ) try: ret = list_security_groups()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The security group \'{0}\' could not be found.'.format(name) ) return ret def get_template_image(kwargs=None, call=None): ''' Returns a template's image from the given template name. .. versionadded:: 2018.3.0 .. code-block:: bash salt-cloud -f get_template_image opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_image function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_image function requires a \'name\'.' ) try: ret = list_templates()[name]['template']['disk']['image'] except KeyError: raise SaltCloudSystemExit( 'The image for template \'{0}\' could not be found.'.format(name) ) return ret def get_template_id(kwargs=None, call=None): ''' Returns a template's ID from the given template name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_template_id opennebula name=my-template-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_template_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_template_id function requires a \'name\'.' ) try: ret = list_templates()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The template \'{0}\' could not be found.'.format(name) ) return ret def get_template(vm_): r''' Return the template id for a VM. .. versionadded:: 2016.11.0 vm\_ The VM dictionary for which to obtain a template. ''' vm_template = six.text_type(config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False )) try: return list_templates()[vm_template]['id'] except KeyError: raise SaltCloudNotFound( 'The specified template, \'{0}\', could not be found.'.format(vm_template) ) def get_vm_id(kwargs=None, call=None): ''' Returns a virtual machine's ID from the given virtual machine's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vm_id opennebula name=my-vm ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vm_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vm_id function requires a name.' ) try: ret = list_nodes()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VM \'{0}\' could not be found.'.format(name) ) return ret def get_vn_id(kwargs=None, call=None): ''' Returns a virtual network's ID from the given virtual network's name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_vn_id opennebula name=my-vn-name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_vn_id function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) if name is None: raise SaltCloudSystemExit( 'The get_vn_id function requires a name.' ) try: ret = list_vns()[name]['id'] except KeyError: raise SaltCloudSystemExit( 'The VN \'{0}\' could not be found.'.format(name) ) return ret def _get_device_template(disk, disk_info, template=None): ''' Returns the template format to create a disk in open nebula .. versionadded:: 2018.3.0 ''' def _require_disk_opts(*args): for arg in args: if arg not in disk_info: raise SaltCloudSystemExit( 'The disk {0} requires a {1}\ argument'.format(disk, arg) ) _require_disk_opts('disk_type', 'size') size = disk_info['size'] disk_type = disk_info['disk_type'] if disk_type == 'clone': if 'image' in disk_info: clone_image = disk_info['image'] else: clone_image = get_template_image(kwargs={'name': template}) clone_image_id = get_image_id(kwargs={'name': clone_image}) temp = 'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\ SIZE={2}]'.format(clone_image, clone_image_id, size) return temp if disk_type == 'volatile': _require_disk_opts('type') v_type = disk_info['type'] temp = 'DISK=[TYPE={0}, SIZE={1}]'.format(v_type, size) if v_type == 'fs': _require_disk_opts('format') format = disk_info['format'] temp = 'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'.format(v_type, size, format) return temp #TODO add persistant disk_type def create(vm_): r''' Create a single VM from a data dict. vm\_ The dictionary use to create a VM. Optional vm\_ dict options for overwriting template: region_id Optional - OpenNebula Zone ID memory Optional - In MB cpu Optional - Percent of host CPU to allocate vcpu Optional - Amount of vCPUs to allocate CLI Example: .. code-block:: bash salt-cloud -p my-opennebula-profile vm_name salt-cloud -p my-opennebula-profile vm_name memory=16384 cpu=2.5 vcpu=16 ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'opennebula', vm_['profile']) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'template_id': get_template(vm_), 'region_id': get_location(vm_), } if 'template' in vm_: kwargs['image_id'] = get_template_id({'name': vm_['template']}) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None ) kwargs['private_networking'] = 'true' if private_networking else 'false' __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), }, sock_dir=__opts__['sock_dir'], ) template = [] if kwargs.get('region_id'): template.append('SCHED_REQUIREMENTS="ID={0}"'.format(kwargs.get('region_id'))) if vm_.get('memory'): template.append('MEMORY={0}'.format(vm_.get('memory'))) if vm_.get('cpu'): template.append('CPU={0}'.format(vm_.get('cpu'))) if vm_.get('vcpu'): template.append('VCPU={0}'.format(vm_.get('vcpu'))) if vm_.get('disk'): get_disks = vm_.get('disk') template_name = vm_['image'] for disk in get_disks: template.append(_get_device_template(disk, get_disks[disk], template=template_name)) if 'CLONE' not in six.text_type(template): raise SaltCloudSystemExit( 'Missing an image disk to clone. Must define a clone disk alongside all other disk definitions.' ) template_args = "\n".join(template) try: server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) cret = server.one.template.instantiate(auth, int(kwargs['template_id']), kwargs['name'], False, template_args) if not cret[0]: log.error( 'Error creating %s on OpenNebula\n\n' 'The following error was returned when trying to ' 'instantiate the template: %s', vm_['name'], cret[1], # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False except Exception as exc: log.error( 'Error creating %s on OpenNebula\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False fqdn = vm_.get('fqdn_base') if fqdn is not None: fqdn = '{0}.{1}'.format(vm_['name'], fqdn) def __query_node_data(vm_name): node_data = show_instance(vm_name, call='action') if not node_data: # Trigger an error in the wait_for_ip function return False if node_data['state'] == '7': return False if node_data['lcm_state'] == '3': return node_data try: data = __utils__['cloud.wait_for_ip']( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=2), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if fqdn: vm_['ssh_host'] = fqdn private_ip = '0.0.0.0' else: try: private_ip = data['private_ips'][0] except KeyError: try: private_ip = data['template']['nic']['ip'] except KeyError: # if IPv6 is used try this as last resort # OpenNebula does not yet show ULA address here so take global private_ip = data['template']['nic']['ip6_global'] vm_['ssh_host'] = private_ip ssh_username = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) vm_['username'] = ssh_username vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret['id'] = data['id'] ret['image'] = vm_['image'] ret['name'] = vm_['name'] ret['size'] = data['template']['memory'] ret['state'] = data['state'] ret['private_ips'] = private_ip ret['public_ips'] = [] log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], ) return ret def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. name The name of the vm to be destroyed. CLI Example: .. code-block:: bash salt-cloud --destroy vm_name salt-cloud -d vm_name salt-cloud --action destroy vm_name salt-cloud -a destroy vm_name ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) data = show_instance(name, call='action') node = server.one.vm.action(auth, 'delete', int(data['id'])) __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir']( name, __active_provider_name__.split(':')[0], __opts__ ) data = { 'action': 'vm.delete', 'deleted': node[0], 'node_id': node[1], 'error_code': node[2] } return data def image_allocate(call=None, kwargs=None): ''' Allocates a new image in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the image to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The data containing the template of the image to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. datastore_id The ID of the data-store to be used for the new image. Can be used instead of ``datastore_name``. datastore_name The name of the data-store to be used for the new image. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -f image_allocate opennebula path=/path/to/image_file.txt datastore_id=1 salt-cloud -f image_allocate opennebula datastore_name=default \\ data='NAME="Ubuntu 14.04" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION="Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both a \'datastore_id\' and a \'datastore_name\' were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The image_allocate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_allocate function requires either a file \'path\' or \'data\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.allocate(auth, data, int(datastore_id)) ret = { 'action': 'image.allocate', 'allocated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def image_clone(call=None, kwargs=None): ''' Clones an existing image. .. versionadded:: 2016.3.0 name The name of the new image. image_id The ID of the image to be cloned. Can be used instead of ``image_name``. image_name The name of the image to be cloned. Can be used instead of ``image_id``. CLI Example: .. code-block:: bash salt-cloud -f image_clone opennebula name=my-new-image image_id=10 salt-cloud -f image_clone opennebula name=my-new-image image_name=my-image-to-clone ''' if call != 'function': raise SaltCloudSystemExit( 'The image_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) if name is None: raise SaltCloudSystemExit( 'The image_clone function requires a \'name\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_clone function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.clone(auth, int(image_id), name) data = { 'action': 'image.clone', 'cloned': response[0], 'cloned_image_id': response[1], 'cloned_image_name': name, 'error_code': response[2], } return data def image_delete(call=None, kwargs=None): ''' Deletes the given image from OpenNebula. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image to delete. Can be used instead of ``image_id``. image_id The ID of the image to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_delete opennebula name=my-image salt-cloud --function image_delete opennebula image_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_delete function requires either an \'image_id\' or a ' '\'name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.delete(auth, int(image_id)) data = { 'action': 'image.delete', 'deleted': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_info(call=None, kwargs=None): ''' Retrieves information for a given image. Either a name or an image_id must be supplied. .. versionadded:: 2016.3.0 name The name of the image for which to gather information. Can be used instead of ``image_id``. image_id The ID of the image for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f image_info opennebula name=my-image salt-cloud --function image_info opennebula image_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) image_id = kwargs.get('image_id', None) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_info function requires either a \'name or an \'image_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.image.info(auth, int(image_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def image_persistent(call=None, kwargs=None): ''' Sets the Image as persistent or not persistent. .. versionadded:: 2016.3.0 name The name of the image to set. Can be used instead of ``image_id``. image_id The ID of the image to set. Can be used instead of ``name``. persist A boolean value to set the image as persistent or not. Set to true for persistent, false for non-persistent. CLI Example: .. code-block:: bash salt-cloud -f image_persistent opennebula name=my-image persist=True salt-cloud --function image_persistent opennebula image_id=5 persist=False ''' if call != 'function': raise SaltCloudSystemExit( 'The image_persistent function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) persist = kwargs.get('persist', None) image_id = kwargs.get('image_id', None) if persist is None: raise SaltCloudSystemExit( 'The image_persistent function requires \'persist\' to be set to \'True\' ' 'or \'False\'.' ) if image_id: if name: log.warning( 'Both the \'image_id\' and \'name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif name: image_id = get_image_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The image_persistent function requires either a \'name\' or an ' '\'image_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.persistent(auth, int(image_id), salt.utils.data.is_true(persist)) data = { 'action': 'image.persistent', 'response': response[0], 'image_id': response[1], 'error_code': response[2], } return data def image_snapshot_delete(call=None, kwargs=None): ''' Deletes a snapshot from the image. .. versionadded:: 2016.3.0 image_id The ID of the image from which to delete the snapshot. Can be used instead of ``image_name``. image_name The name of the image from which to delete the snapshot. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to delete. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_delete vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_delete vm_name=my-vm snapshot_id=111 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_delete function requires either an \'image_id\' ' 'or a \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_revert(call=None, kwargs=None): ''' Reverts an image state to a previous snapshot. .. versionadded:: 2016.3.0 image_id The ID of the image to revert. Can be used instead of ``image_name``. image_name The name of the image to revert. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to which the image will be reverted. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_revert vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_revert vm_name=my-vm snapshot_id=120 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_revert function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_revert function requires either an \'image_id\' or ' 'an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotrevert(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotrevert', 'reverted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_snapshot_flatten(call=None, kwargs=None): ''' Flattens the snapshot of an image and discards others. .. versionadded:: 2016.3.0 image_id The ID of the image. Can be used instead of ``image_name``. image_name The name of the image. Can be used instead of ``image_id``. snapshot_id The ID of the snapshot to flatten. CLI Example: .. code-block:: bash salt-cloud -f image_snapshot_flatten vm_id=106 snapshot_id=45 salt-cloud -f image_snapshot_flatten vm_name=my-vm snapshot_id=45 ''' if call != 'function': raise SaltCloudSystemExit( 'The image_snapshot_flatten function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The image_stanpshot_flatten function requires a \'snapshot_id\' ' 'to be provided.' ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_snapshot_flatten function requires either an ' '\'image_id\' or an \'image_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.snapshotflatten(auth, int(image_id), int(snapshot_id)) data = { 'action': 'image.snapshotflatten', 'flattened': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def image_update(call=None, kwargs=None): ''' Replaces the image template contents. .. versionadded:: 2016.3.0 image_id The ID of the image to update. Can be used instead of ``image_name``. image_name The name of the image to update. Can be used instead of ``image_id``. path The path to a file containing the template of the image. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the image. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update an image: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -f image_update opennebula image_id=0 file=/path/to/image_update_file.txt update_type=replace salt-cloud -f image_update opennebula image_name="Ubuntu 14.04" update_type=merge \\ data='NAME="Ubuntu Dev" PATH="/home/one_user/images/ubuntu_desktop.img" \\ DESCRIPTION = "Ubuntu 14.04 for development."' ''' if call != 'function': raise SaltCloudSystemExit( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The image_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if image_id: if image_name: log.warning( 'Both the \'image_id\' and \'image_name\' arguments were provided. ' '\'image_id\' will take precedence.' ) elif image_name: image_id = get_image_id(kwargs={'name': image_name}) else: raise SaltCloudSystemExit( 'The image_update function requires either an \'image_id\' or an ' '\'image_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The image_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.image.update(auth, int(image_id), data, int(update_number)) ret = { 'action': 'image.update', 'updated': response[0], 'image_id': response[1], 'error_code': response[2], } return ret def show_instance(name, call=None): ''' Show the details from OpenNebula concerning a named VM. name The name of the VM for which to display details. call Type of call to use with this function such as ``function``. CLI Example: .. code-block:: bash salt-cloud --action show_instance vm_name salt-cloud -a show_instance vm_name ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def secgroup_allocate(call=None, kwargs=None): ''' Allocates a new security group in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_allocate opennebula path=/path/to/secgroup_file.txt salt-cloud -f secgroup_allocate opennebula \\ data="NAME = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, \\ RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.allocate(auth, data) ret = { 'action': 'secgroup.allocate', 'allocated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def secgroup_clone(call=None, kwargs=None): ''' Clones an existing security group. .. versionadded:: 2016.3.0 name The name of the new template. secgroup_id The ID of the security group to be cloned. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to be cloned. Can be used instead of ``secgroup_id``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_id=0 salt-cloud -f secgroup_clone opennebula name=my-cloned-secgroup secgroup_name=my-secgroup ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) if name is None: raise SaltCloudSystemExit( 'The secgroup_clone function requires a \'name\' to be provided.' ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_clone function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.clone(auth, int(secgroup_id), name) data = { 'action': 'secgroup.clone', 'cloned': response[0], 'cloned_secgroup_id': response[1], 'cloned_secgroup_name': name, 'error_code': response[2], } return data def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data def secgroup_info(call=None, kwargs=None): ''' Retrieves information for the given security group. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group for which to gather information. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_info opennebula name=my-secgroup salt-cloud --function secgroup_info opennebula secgroup_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_info function requires either a name or a secgroup_id ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) info = {} response = server.one.secgroup.info(auth, int(secgroup_id))[1] tree = _get_xml(response) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def secgroup_update(call=None, kwargs=None): ''' Replaces the security group template contents. .. versionadded:: 2016.3.0 secgroup_id The ID of the security group to update. Can be used instead of ``secgroup_name``. secgroup_name The name of the security group to update. Can be used instead of ``secgroup_id``. path The path to a file containing the template of the security group. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data The template data of the security group. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a security group: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function secgroup_update opennebula secgroup_id=100 \\ path=/path/to/secgroup_update_file.txt \\ update_type=replace salt-cloud -f secgroup_update opennebula secgroup_name=my-secgroup update_type=merge \\ data="Name = test RULE = [PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 1000:2000]" ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} secgroup_id = kwargs.get('secgroup_id', None) secgroup_name = kwargs.get('secgroup_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The secgroup_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if secgroup_id: if secgroup_name: log.warning( 'Both the \'secgroup_id\' and \'secgroup_name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif secgroup_name: secgroup_id = get_secgroup_id(kwargs={'name': secgroup_name}) else: raise SaltCloudSystemExit( 'The secgroup_update function requires either a \'secgroup_id\' or a ' '\'secgroup_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The secgroup_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.update(auth, int(secgroup_id), data, int(update_number)) ret = { 'action': 'secgroup.update', 'updated': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return ret def template_allocate(call=None, kwargs=None): ''' Allocates a new template in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the elements of the template to be allocated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be allocated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f template_allocate opennebula path=/path/to/template_file.txt salt-cloud -f template_allocate opennebula \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_allocate function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.allocate(auth, data) ret = { 'action': 'template.allocate', 'allocated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def template_clone(call=None, kwargs=None): ''' Clones an existing virtual machine template. .. versionadded:: 2016.3.0 name The name of the new template. template_id The ID of the template to be cloned. Can be used instead of ``template_name``. template_name The name of the template to be cloned. Can be used instead of ``template_id``. clone_images Optional, defaults to False. Indicates if the images attached to the template should be cloned as well. CLI Example: .. code-block:: bash salt-cloud -f template_clone opennebula name=my-new-template template_id=0 salt-cloud -f template_clone opennebula name=my-new-template template_name=my-template ''' if call != 'function': raise SaltCloudSystemExit( 'The template_clone function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) clone_images = kwargs.get('clone_images', False) if name is None: raise SaltCloudSystemExit( 'The template_clone function requires a name to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_clone function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.clone(auth, int(template_id), name, clone_images) data = { 'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2], } return data def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f template_delete opennebula name=my-template salt-cloud --function template_delete opennebula template_id=5 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) template_id = kwargs.get('template_id', None) if template_id: if name: log.warning( 'Both the \'template_id\' and \'name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif name: template_id = get_template_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The template_delete function requires either a \'name\' or a \'template_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.delete(auth, int(template_id)) data = { 'action': 'template.delete', 'deleted': response[0], 'template_id': response[1], 'error_code': response[2], } return data def template_instantiate(call=None, kwargs=None): ''' Instantiates a new virtual machine from a template. .. versionadded:: 2016.3.0 .. note:: ``template_instantiate`` creates a VM on OpenNebula from a template, but it does not install Salt on the new VM. Use the ``create`` function for that functionality: ``salt-cloud -p opennebula-profile vm-name``. vm_name Name for the new VM instance. template_id The ID of the template from which the VM will be created. Can be used instead of ``template_name``. template_name The name of the template from which the VM will be created. Can be used instead of ``template_id``. CLI Example: .. code-block:: bash salt-cloud -f template_instantiate opennebula vm_name=my-new-vm template_id=0 ''' if call != 'function': raise SaltCloudSystemExit( 'The template_instantiate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vm_name = kwargs.get('vm_name', None) template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) if vm_name is None: raise SaltCloudSystemExit( 'The template_instantiate function requires a \'vm_name\' to be provided.' ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_instantiate function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.instantiate(auth, int(template_id), vm_name) data = { 'action': 'template.instantiate', 'instantiated': response[0], 'instantiated_vm_id': response[1], 'vm_name': vm_name, 'error_code': response[2], } return data def template_update(call=None, kwargs=None): ''' Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the elements of the template to be updated. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the elements of the template to be updated. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a template: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud --function template_update opennebula template_id=1 update_type=replace \\ path=/path/to/template_update_file.txt salt-cloud -f template_update opennebula template_name=my-template update_type=merge \\ data='CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ VCPU="1"' ''' if call != 'function': raise SaltCloudSystemExit( 'The template_update function must be called with -f or --function.' ) if kwargs is None: kwargs = {} template_id = kwargs.get('template_id', None) template_name = kwargs.get('template_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The template_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if template_id: if template_name: log.warning( 'Both the \'template_id\' and \'template_name\' arguments were provided. ' '\'template_id\' will take precedence.' ) elif template_name: template_id = get_template_id(kwargs={'name': template_name}) else: raise SaltCloudSystemExit( 'The template_update function requires either a \'template_id\' ' 'or a \'template_name\' to be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The template_update function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.template.update(auth, int(template_id), data, int(update_number)) ret = { 'action': 'template.update', 'updated': response[0], 'template_id': response[1], 'error_code': response[2], } return ret def vm_action(name, kwargs=None, call=None): ''' Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - poweroff - poweroff-hard - reboot - reboot-hard - release - resched - resume - shutdown - shutdown-hard - stop - suspend - undeploy - undeploy-hard - unresched CLI Example: .. code-block:: bash salt-cloud -a vm_action my-vm action='release' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_action function must be called with -a or --action.' ) if kwargs is None: kwargs = {} action = kwargs.get('action', None) if action is None: raise SaltCloudSystemExit( 'The vm_action function must have an \'action\' provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.action(auth, action, vm_id) data = { 'action': 'vm.action.' + six.text_type(action), 'actioned': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_allocate(call=None, kwargs=None): ''' Allocates a new virtual machine in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file defining the template of the VM to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template definitions of the VM to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. hold If this parameter is set to ``True``, the VM will be created in the ``HOLD`` state. If not set, the VM is created in the ``PENDING`` state. Default is ``False``. CLI Example: .. code-block:: bash salt-cloud -f vm_allocate path=/path/to/vm_template.txt salt-cloud --function vm_allocate path=/path/to/vm_template.txt hold=True ''' if call != 'function': raise SaltCloudSystemExit( 'The vm_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) hold = kwargs.get('hold', False) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vm.allocate(auth, data, salt.utils.data.is_true(hold)) ret = { 'action': 'vm.allocate', 'allocated': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach(name, kwargs=None, call=None): ''' Attaches a new disk to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new disk. path The path to a file containing a single disk vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the data needed to attach a single disk vector attribute. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach my-vm path=/path/to/disk_file.txt salt-cloud -a vm_attach my-vm data="DISK=[DISK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attach(auth, vm_id, data) ret = { 'action': 'vm.attach', 'attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_attach_nic(name, kwargs=None, call=None): ''' Attaches a new network interface to the given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM for which to attach the new network interface. path The path to a file containing a single NIC vector attribute. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the single NIC vector attribute to attach to the VM. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -a vm_attach_nic my-vm path=/path/to/nic_file.txt salt-cloud -a vm_attach_nic my-vm data="NIC=[NETWORK_ID=1]" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_attach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_attach_nic function requires either \'data\' or a file ' '\'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.attachnic(auth, vm_id, data) ret = { 'action': 'vm.attachnic', 'nic_attached': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. host_name The name of the target host where the VM will be deployed. Can be used instead of ``host_id``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The ID of the target system data-store where the VM will be deployed. Optional and can be used instead of ``datastore_name``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. datastore_name The name of the target system data-store where the VM will be deployed. Optional, and can be used instead of ``datastore_id``. If neither ``datastore_id`` nor ``datastore_name`` are set, OpenNebula will choose the data-store. CLI Example: .. code-block:: bash salt-cloud -a vm_deploy my-vm host_id=0 salt-cloud -a vm_deploy my-vm host_id=1 capacity_maintained=False salt-cloud -a vm_deploy my-vm host_name=host01 datastore_id=1 salt-cloud -a vm_deploy my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_deploy action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_deploy function requires a \'host_id\' or a \'host_name\' ' 'to be provided.' ) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: datastore_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = get_vm_id(kwargs={'name': name}) response = server.one.vm.deploy(auth, int(vm_id), int(host_id), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.deploy', 'deployed': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the disk. disk_id The ID of the disk to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach my-vm disk_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) if disk_id is None: raise SaltCloudSystemExit( 'The vm_detach function requires a \'disk_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detach(auth, vm_id, int(disk_id)) data = { 'action': 'vm.detach', 'detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_detach_nic action must be called with -a or --action.' ) if kwargs is None: kwargs = {} nic_id = kwargs.get('nic_id', None) if nic_id is None: raise SaltCloudSystemExit( 'The vm_detach_nic function requires a \'nic_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.detachnic(auth, vm_id, int(nic_id)) data = { 'action': 'vm.detachnic', 'nic_detached': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk will be saved. image_type The type for the new image. If not set, then the default ``ONED`` Configuration will be used. Other valid types include: OS, CDROM, DATABLOCK, KERNEL, RAMDISK, and CONTEXT. snapshot_id The ID of the snapshot to export. If not set, the current image state will be used. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image salt-cloud -a vm_disk_save my-vm disk_id=1 image_name=my-new-image image_type=CONTEXT snapshot_id=10 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_save action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) image_name = kwargs.get('image_name', None) image_type = kwargs.get('image_type', '') snapshot_id = int(kwargs.get('snapshot_id', '-1')) if disk_id is None or image_name is None: raise SaltCloudSystemExit( 'The vm_disk_save function requires a \'disk_id\' and an \'image_name\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksave(auth, vm_id, int(disk_id), image_name, image_type, snapshot_id) data = { 'action': 'vm.disksave', 'saved': response[0], 'image_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_create my-vm disk_id=0 description="My Snapshot Description" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) description = kwargs.get('description', None) if disk_id is None or description is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'description\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotcreate(auth, vm_id, int(disk_id), description) data = { 'action': 'vm.disksnapshotcreate', 'created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_delete(name, kwargs=None, call=None): ''' Deletes a disk snapshot based on the given VM and the disk_id. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot to delete. disk_id The ID of the disk to save. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_delete my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_create function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotdelete(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_disk_snapshot_revert(name, kwargs=None, call=None): ''' Reverts a disk state to a previously taken snapshot. .. versionadded:: 2016.3.0 name The name of the VM containing the snapshot. disk_id The ID of the disk to revert its state. snapshot_id The ID of the snapshot to which the snapshot should be reverted. CLI Example: .. code-block:: bash salt-cloud -a vm_disk_snapshot_revert my-vm disk_id=0 snapshot_id=6 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} disk_id = kwargs.get('disk_id', None) snapshot_id = kwargs.get('snapshot_id', None) if disk_id is None or snapshot_id is None: raise SaltCloudSystemExit( 'The vm_disk_snapshot_revert function requires a \'disk_id\' and a \'snapshot_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.disksnapshotrevert(auth, vm_id, int(disk_id), int(snapshot_id)) data = { 'action': 'vm.disksnapshotrevert', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_info action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.info(auth, vm_id) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vm_migrate(name, kwargs=None, call=None): ''' Migrates the specified virtual machine to the specified target host. .. versionadded:: 2016.3.0 name The name of the VM to migrate. host_id The ID of the host to which the VM will be migrated. Can be used instead of ``host_name``. host_name The name of the host to which the VM will be migrated. Can be used instead of ``host_id``. live_migration If set to ``True``, a live-migration will be performed. Default is ``False``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. datastore_id The target system data-store ID where the VM will be migrated. Can be used instead of ``datastore_name``. datastore_name The name of the data-store target system where the VM will be migrated. Can be used instead of ``datastore_id``. CLI Example: .. code-block:: bash salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 salt-cloud -a vm_migrate my-vm host_id=0 datastore_id=1 live_migration=True salt-cloud -a vm_migrate my-vm host_name=host01 datastore_name=default ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_migrate action must be called with -a or --action.' ) if kwargs is None: kwargs = {} host_id = kwargs.get('host_id', None) host_name = kwargs.get('host_name', None) live_migration = kwargs.get('live_migration', False) capacity_maintained = kwargs.get('capacity_maintained', True) datastore_id = kwargs.get('datastore_id', None) datastore_name = kwargs.get('datastore_name', None) if datastore_id: if datastore_name: log.warning( 'Both the \'datastore_id\' and \'datastore_name\' arguments were provided. ' '\'datastore_id\' will take precedence.' ) elif datastore_name: datastore_id = get_datastore_id(kwargs={'name': datastore_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'datastore_id\' or a ' '\'datastore_name\' to be provided.' ) if host_id: if host_name: log.warning( 'Both the \'host_id\' and \'host_name\' arguments were provided. ' '\'host_id\' will take precedence.' ) elif host_name: host_id = get_host_id(kwargs={'name': host_name}) else: raise SaltCloudSystemExit( 'The vm_migrate function requires either a \'host_id\' ' 'or a \'host_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.migrate(auth, vm_id, int(host_id), salt.utils.data.is_true(live_migration), salt.utils.data.is_true(capacity_maintained), int(datastore_id)) data = { 'action': 'vm.migrate', 'migrated': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_monitoring(name, call=None): ''' Returns the monitoring records for a given virtual machine. A VM name must be supplied. The monitoring information returned is a list of VM elements. Each VM element contains the complete dictionary of the VM with the updated information returned by the poll action. .. versionadded:: 2016.3.0 name The name of the VM for which to gather monitoring records. CLI Example: .. code-block:: bash salt-cloud -a vm_monitoring my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_monitoring action must be called with -a or --action.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.monitoring(auth, vm_id) if response[0] is False: log.error( 'There was an error retrieving the specified VM\'s monitoring ' 'information.' ) return {} else: info = {} for vm_ in _get_xml(response[1]): info[vm_.find('ID').text] = _xml_to_dict(vm_) return info def vm_resize(name, kwargs=None, call=None): ''' Changes the capacity of the virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to resize. path The path to a file containing new capacity elements CPU, VCPU, MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new capacity elements CPU, VCPU, and MEMORY. If one of them is not present, or its value is 0, the VM will not be re-sized. Can be used instead of ``path``. capacity_maintained True to enforce the Host capacity is not over-committed. This parameter is only acknowledged for users in the ``oneadmin`` group. Host capacity will be always enforced for regular users. CLI Example: .. code-block:: bash salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt salt-cloud -a vm_resize my-vm path=/path/to/capacity_template.txt capacity_maintained=False salt-cloud -a vm_resize my-vm data="CPU=1 VCPU=1 MEMORY=1024" ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_resize action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) capacity_maintained = kwargs.get('capacity_maintained', True) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_resize function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.resize(auth, vm_id, data, salt.utils.data.is_true(capacity_maintained)) ret = { 'action': 'vm.resize', 'resized': response[0], 'vm_id': response[1], 'error_code': response[2], } return ret def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create my-vm snapshot_name=my-new-snapshot ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_create action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get('snapshot_name', None) if snapshot_name is None: raise SaltCloudSystemExit( 'The vm_snapshot_create function requires a \'snapshot_name\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotcreate(auth, vm_id, snapshot_name) data = { 'action': 'vm.snapshotcreate', 'snapshot_created': response[0], 'snapshot_id': response[1], 'error_code': response[2], } return data def vm_snapshot_delete(vm_name, kwargs=None, call=None): ''' Deletes a virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to delete the snapshot. snapshot_id The ID of the snapshot to be deleted. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_delete my-vm snapshot_id=8 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_delete action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_delete function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotdelete(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotdelete', 'snapshot_deleted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_snapshot_revert(vm_name, kwargs=None, call=None): ''' Reverts a virtual machine to a snapshot .. versionadded:: 2016.3.0 vm_name The name of the VM to revert. snapshot_id The snapshot ID. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_revert my-vm snapshot_id=42 ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_snapshot_revert action must be called with -a or --action.' ) if kwargs is None: kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if snapshot_id is None: raise SaltCloudSystemExit( 'The vm_snapshot_revert function requires a \'snapshot_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = { 'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2], } return data def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the new user template contents. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. update_type There are two ways to update a VM: ``replace`` the whole template or ``merge`` the new template with the existing one. CLI Example: .. code-block:: bash salt-cloud -a vm_update my-vm path=/path/to/user_template_file.txt update_type='replace' ''' if call != 'action': raise SaltCloudSystemExit( 'The vm_update action must be called with -a or --action.' ) if kwargs is None: kwargs = {} path = kwargs.get('path', None) data = kwargs.get('data', None) update_type = kwargs.get('update_type', None) update_args = ['replace', 'merge'] if update_type is None: raise SaltCloudSystemExit( 'The vm_update function requires an \'update_type\' to be provided.' ) if update_type == update_args[0]: update_number = 0 elif update_type == update_args[1]: update_number = 1 else: raise SaltCloudSystemExit( 'The update_type argument must be either {0} or {1}.'.format( update_args[0], update_args[1] ) ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vm_update function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': name})) response = server.one.vm.update(auth, vm_id, data, int(update_number)) ret = { 'action': 'vm.update', 'updated': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_add_ar(call=None, kwargs=None): ''' Adds address ranges to a given virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network to add the address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network to add the address range. Can be used instead of ``vn_id``. path The path to a file containing the template of the address range to add. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the address range to add. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_add_ar opennebula vn_id=3 path=/path/to/address_range.txt salt-cloud -f vn_add_ar opennebula vn_name=my-vn \\ data="AR=[TYPE=IP4, IP=192.168.0.5, SIZE=10]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_add_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_add_ar function requires a \'vn_id\' and a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_add_ar function requires either \'data\' or a file \'path\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.add_ar(auth, int(vn_id), data) ret = { 'action': 'vn.add_ar', 'address_range_added': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the virtual network to allocate. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. cluster_id The ID of the cluster for which to add the new virtual network. Can be used instead of ``cluster_name``. If neither ``cluster_id`` nor ``cluster_name`` are provided, the virtual network won’t be added to any cluster. cluster_name The name of the cluster for which to add the new virtual network. Can be used instead of ``cluster_id``. If neither ``cluster_name`` nor ``cluster_id`` are provided, the virtual network won't be added to any cluster. CLI Example: .. code-block:: bash salt-cloud -f vn_allocate opennebula path=/path/to/vn_file.txt ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_allocate function must be called with -f or --function.' ) if kwargs is None: kwargs = {} cluster_id = kwargs.get('cluster_id', None) cluster_name = kwargs.get('cluster_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_allocate function requires either \'data\' or a file \'path\' ' 'to be provided.' ) if cluster_id: if cluster_name: log.warning( 'Both the \'cluster_id\' and \'cluster_name\' arguments were provided. ' '\'cluster_id\' will take precedence.' ) elif cluster_name: cluster_id = get_cluster_id(kwargs={'name': cluster_name}) else: cluster_id = '-1' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.allocate(auth, data, int(cluster_id)) ret = { 'action': 'vn.allocate', 'allocated': response[0], 'vn_id': response[1], 'error_code': response[2], } return ret def vn_delete(call=None, kwargs=None): ''' Deletes the given virtual network from OpenNebula. Either a name or a vn_id must be supplied. .. versionadded:: 2016.3.0 name The name of the virtual network to delete. Can be used instead of ``vn_id``. vn_id The ID of the virtual network to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_delete opennebula name=my-virtual-network salt-cloud --function vn_delete opennebula vn_id=3 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_delete function requires a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = { 'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2], } return data def vn_free_ar(call=None, kwargs=None): ''' Frees a reserved address range from a virtual network. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to free an address range. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to free an address range. Can be used instead of ``vn_id``. ar_id The ID of the address range to free. CLI Example: .. code-block:: bash salt-cloud -f vn_free_ar opennebula vn_id=3 ar_id=1 salt-cloud -f vn_free_ar opennebula vn_name=my-vn ar_id=1 ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) ar_id = kwargs.get('ar_id', None) if ar_id is None: raise SaltCloudSystemExit( 'The vn_free_ar function requires an \'rn_id\' to be provided.' ) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_free_ar function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.free_ar(auth, int(vn_id), int(ar_id)) data = { 'action': 'vn.free_ar', 'ar_freed': response[0], 'resource_id': response[1], 'error_code': response[2], } return data def vn_hold(call=None, kwargs=None): ''' Holds a virtual network lease as used. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to hold the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to hold the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to hold. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template of the lease to hold. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_hold opennebula vn_id=3 path=/path/to/vn_hold_file.txt salt-cloud -f vn_hold opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_hold function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_hold function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_hold function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.hold(auth, int(vn_id), data) ret = { 'action': 'vn.hold', 'held': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f vn_info opennebula vn_id=3 salt-cloud --function vn_info opennebula name=public ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_info function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning( 'Both the \'vn_id\' and \'name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The vn_info function requires either a \'name\' or a \'vn_id\' ' 'to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.info(auth, int(vn_id)) if response[0] is False: return response[1] else: info = {} tree = _get_xml(response[1]) info[tree.find('NAME').text] = _xml_to_dict(tree) return info def vn_release(call=None, kwargs=None): ''' Releases a virtual network lease that was previously on hold. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to release the lease. Can be used instead of ``vn_name``. vn_name The name of the virtual network from which to release the lease. Can be used instead of ``vn_id``. path The path to a file defining the template of the lease to release. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the lease to release. Syntax can be the usual attribute=value or XML. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_release opennebula vn_id=3 path=/path/to/vn_release_file.txt salt-cloud =f vn_release opennebula vn_name=my-vn data="LEASES=[IP=192.168.0.5]" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_release function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_release function requires either \'data\' or a \'path\' to ' 'be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.release(auth, int(vn_id), data) ret = { 'action': 'vn.release', 'released': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret def vn_reserve(call=None, kwargs=None): ''' Reserve network addresses. .. versionadded:: 2016.3.0 vn_id The ID of the virtual network from which to reserve addresses. Can be used instead of vn_name. vn_name The name of the virtual network from which to reserve addresses. Can be used instead of vn_id. path The path to a file defining the template of the address reservation. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the template defining the address reservation. Syntax can be the usual attribute=value or XML. Data provided must be wrapped in double quotes. Can be used instead of ``path``. CLI Example: .. code-block:: bash salt-cloud -f vn_reserve opennebula vn_id=3 path=/path/to/vn_reserve_file.txt salt-cloud -f vn_reserve opennebula vn_name=my-vn data="SIZE=10 AR_ID=8 NETWORK_ID=1" ''' if call != 'function': raise SaltCloudSystemExit( 'The vn_reserve function must be called with -f or --function.' ) if kwargs is None: kwargs = {} vn_id = kwargs.get('vn_id', None) vn_name = kwargs.get('vn_name', None) path = kwargs.get('path', None) data = kwargs.get('data', None) if vn_id: if vn_name: log.warning( 'Both the \'vn_id\' and \'vn_name\' arguments were provided. ' '\'vn_id\' will take precedence.' ) elif vn_name: vn_id = get_vn_id(kwargs={'name': vn_name}) else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'vn_id\' or a \'vn_name\' to ' 'be provided.' ) if data: if path: log.warning( 'Both the \'data\' and \'path\' arguments were provided. ' '\'data\' will take precedence.' ) elif path: with salt.utils.files.fopen(path, mode='r') as rfh: data = rfh.read() else: raise SaltCloudSystemExit( 'The vn_reserve function requires a \'path\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.reserve(auth, int(vn_id), data) ret = { 'action': 'vn.reserve', 'reserved': response[0], 'resource_id': response[1], 'error_code': response[2], } return ret # Helper Functions def _get_node(name): ''' Helper function that returns all information about a named node. name The name of the node for which to get information. ''' attempts = 10 while attempts >= 0: try: return list_nodes_full()[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it raise SaltCloudSystemExit('opennebula returned: {0}'.format(xml_str)) return xml_data def _get_xml_rpc(): ''' Uses the OpenNebula cloud provider configurations to connect to the OpenNebula API. Returns the server connection created as well as the user and password values from the cloud provider config file used to make the connection. ''' vm_ = get_configured_provider() xml_rpc = config.get_cloud_config_value( 'xml_rpc', vm_, __opts__, search_global=False ) user = config.get_cloud_config_value( 'user', vm_, __opts__, search_global=False ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc) return server, user, password def _list_nodes(full=False): ''' Helper function for the list_* query functions - Constructs the appropriate dictionaries to return from the API query. full If performing a full query, such as in list_nodes_full, change this parameter to ``True``. ''' server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) vm_pool = server.one.vmpool.info(auth, -2, -1, -1, -1)[1] vms = {} for vm in _get_xml(vm_pool): name = vm.find('NAME').text vms[name] = {} cpu_size = vm.find('TEMPLATE').find('CPU').text memory_size = vm.find('TEMPLATE').find('MEMORY').text private_ips = [] for nic in vm.find('TEMPLATE').findall('NIC'): try: private_ips.append(nic.find('IP').text) except Exception: pass vms[name]['id'] = vm.find('ID').text if 'TEMPLATE_ID' in vm.find('TEMPLATE'): vms[name]['image'] = vm.find('TEMPLATE').find('TEMPLATE_ID').text vms[name]['name'] = name vms[name]['size'] = {'cpu': cpu_size, 'memory': memory_size} vms[name]['state'] = vm.find('STATE').text vms[name]['private_ips'] = private_ips vms[name]['public_ips'] = [] if full: vms[vm.find('NAME').text] = _xml_to_dict(vm) return vms
saltstack/salt
salt/modules/config.py
option
python
def option( value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Pass in a generic option and receive the value that will be assigned CLI Example: .. code-block:: bash salt '*' config.option redis.host ''' if not omit_opts: if value in __opts__: return __opts__[value] if not omit_master: if value in __pillar__.get('master', {}): return __pillar__['master'][value] if not omit_pillar: if value in __pillar__: return __pillar__[value] if value in DEFAULTS: return DEFAULTS[value] return default
Pass in a generic option and receive the value that will be assigned CLI Example: .. code-block:: bash salt '*' config.option redis.host
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/config.py#L131-L157
null
# -*- coding: utf-8 -*- ''' Return config information ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import re import os import logging # Import salt libs import salt.config import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.platform try: # Gated for salt-ssh (salt.utils.cloud imports msgpack) import salt.utils.cloud HAS_CLOUD = True except ImportError: HAS_CLOUD = False import salt._compat import salt.syspaths as syspaths import salt.utils.sdb as sdb # Import 3rd-party libs from salt.ext import six if salt.utils.platform.is_windows(): _HOSTS_FILE = os.path.join( os.environ['SystemRoot'], 'System32', 'drivers', 'etc', 'hosts') else: _HOSTS_FILE = os.path.join(os.sep, 'etc', 'hosts') log = logging.getLogger(__name__) __proxyenabled__ = ['*'] # Set up the default values for all systems DEFAULTS = {'mongo.db': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': '', 'redis.db': '0', 'redis.host': 'salt', 'redis.port': 6379, 'test.foo': 'unconfigured', 'ca.cert_base_path': '/etc/pki', 'solr.cores': [], 'solr.host': 'localhost', 'solr.port': '8983', 'solr.baseurl': '/solr', 'solr.type': 'master', 'solr.request_timeout': None, 'solr.init_script': '/etc/rc.d/solr', 'solr.dih.import_options': {'clean': False, 'optimize': True, 'commit': True, 'verbose': False}, 'solr.backup_path': None, 'solr.num_backups': 1, 'poudriere.config': '/usr/local/etc/poudriere.conf', 'poudriere.config_dir': '/usr/local/etc/poudriere.d', 'ldap.uri': '', 'ldap.server': 'localhost', 'ldap.port': '389', 'ldap.tls': False, 'ldap.no_verify': False, 'ldap.anonymous': True, 'ldap.scope': 2, 'ldap.attrs': None, 'ldap.binddn': '', 'ldap.bindpw': '', 'hosts.file': _HOSTS_FILE, 'aliases.file': '/etc/aliases', 'virt': {'tunnel': False, 'images': os.path.join(syspaths.SRV_ROOT_DIR, 'salt-images')}, } def backup_mode(backup=''): ''' Return the backup mode CLI Example: .. code-block:: bash salt '*' config.backup_mode ''' if backup: return backup return option('backup_mode') def manage_mode(mode): ''' Return a mode value, normalized to a string CLI Example: .. code-block:: bash salt '*' config.manage_mode ''' # config.manage_mode should no longer be invoked from the __salt__ dunder # in Salt code, this function is only being left here for backwards # compatibility. return salt.utils.files.normalize_mode(mode) def valid_fileproto(uri): ''' Returns a boolean value based on whether or not the URI passed has a valid remote file protocol designation CLI Example: .. code-block:: bash salt '*' config.valid_fileproto salt://path/to/file ''' try: return bool(re.match('^(?:salt|https?|ftp)://', uri)) except Exception: return False def merge(value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Retrieves an option based on key, merging all matches. Same as ``option()`` except that it merges all matches, rather than taking the first match. CLI Example: .. code-block:: bash salt '*' config.merge schedule ''' ret = None if not omit_opts: if value in __opts__: ret = __opts__[value] if isinstance(ret, six.string_types): return ret if not omit_master: if value in __pillar__.get('master', {}): tmp = __pillar__['master'][value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if not omit_pillar: if value in __pillar__: tmp = __pillar__[value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if ret is None and value in DEFAULTS: return DEFAULTS[value] if ret is None: return default return ret def get(key, default='', delimiter=':', merge=None, omit_opts=False, omit_pillar=False, omit_master=False, omit_grains=False): ''' .. versionadded: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master config. If the named value is not available, return the value specified by ``default``. If not specified, the default is an empty string. Values can also be retrieved from nested dictionaries. Assume the below data structure: .. code-block:: python {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key, in the sub-dictionary corresponding to the ``pkg`` key, the following command can be used: .. code-block:: bash salt myminion config.get pkg:apache The ``:`` (colon) is used to represent a nested dictionary level. .. versionchanged:: 2015.5.0 The ``delimiter`` argument was added, to allow delimiters other than ``:`` to be used. This function traverses these data stores in this order, returning the first match found: - Minion configuration - Minion's grains - Minion's pillar data - Master configuration (requires :conf_minion:`pillar_opts` to be set to ``True`` in Minion config file in order to work) This means that if there is a value that is going to be the same for the majority of minions, it can be configured in the Master config file, and then overridden using the grains, pillar, or Minion config file. Adding config options to the Master or Minion configuration file is easy: .. code-block:: yaml my-config-option: value cafe-menu: - egg and bacon - egg sausage and bacon - egg and spam - egg bacon and spam - egg bacon sausage and spam - spam bacon sausage and spam - spam egg spam spam bacon and spam - spam sausage spam spam bacon spam tomato and spam .. note:: Minion configuration options built into Salt (like those defined :ref:`here <configuration-salt-minion>`) will *always* be defined in the Minion configuration and thus *cannot be overridden by grains or pillar data*. However, additional (user-defined) configuration options (as in the above example) will not be in the Minion configuration by default and thus can be overridden using grains/pillar data by leaving the option out of the minion config file. **Arguments** delimiter .. versionadded:: 2015.5.0 Override the delimiter used to separate nested levels of a data structure. merge .. versionadded:: 2015.5.0 If passed, this parameter will change the behavior of the function so that, instead of traversing each data store above in order and returning the first match, the data stores are first merged together and then searched. The pillar data is merged into the master config data, then the grains are merged, followed by the Minion config data. The resulting data structure is then searched for a match. This allows for configurations to be more flexible. .. note:: The merging described above does not mean that grain data will end up in the Minion's pillar data, or pillar data will end up in the master config data, etc. The data is just combined for the purposes of searching an amalgam of the different data stores. The supported merge strategies are as follows: - **recurse** - If a key exists in both dictionaries, and the new value is not a dictionary, it is replaced. Otherwise, the sub-dictionaries are merged together into a single dictionary, recursively on down, following the same criteria. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'bar': 1, 'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} - **overwrite** - If a key exists in the top level of both dictionaries, the new value completely overwrites the old. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} CLI Example: .. code-block:: bash salt '*' config.get pkg:apache salt '*' config.get lxc.container_profile:centos merge=recurse ''' if merge is None: if not omit_opts: ret = salt.utils.data.traverse_dict_and_list( __opts__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_grains: ret = salt.utils.data.traverse_dict_and_list( __grains__, key, '_|-', delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_pillar: ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_master: ret = salt.utils.data.traverse_dict_and_list( __pillar__.get('master', {}), key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) ret = salt.utils.data.traverse_dict_and_list( DEFAULTS, key, '_|-', delimiter=delimiter) log.debug("key: %s, ret: %s", key, ret) if ret != '_|-': return sdb.sdb_get(ret, __opts__) else: if merge not in ('recurse', 'overwrite'): log.warning('Unsupported merge strategy \'%s\'. Falling back ' 'to \'recurse\'.', merge) merge = 'recurse' merge_lists = salt.config.master_config('/etc/salt/master').get('pillar_merge_lists') data = copy.copy(DEFAULTS) data = salt.utils.dictupdate.merge(data, __pillar__.get('master', {}), strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __pillar__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __grains__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __opts__, strategy=merge, merge_lists=merge_lists) ret = salt.utils.data.traverse_dict_and_list( data, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) return default def dot_vals(value): ''' Pass in a configuration value that should be preceded by the module name and a dot, this will return a list of all read key/value pairs CLI Example: .. code-block:: bash salt '*' config.dot_vals host ''' ret = {} for key, val in six.iteritems(__pillar__.get('master', {})): if key.startswith('{0}.'.format(value)): ret[key] = val for key, val in six.iteritems(__opts__): if key.startswith('{0}.'.format(value)): ret[key] = val return ret def gather_bootstrap_script(bootstrap=None): ''' Download the salt-bootstrap script, and return its location bootstrap URL of alternate bootstrap script CLI Example: .. code-block:: bash salt '*' config.gather_bootstrap_script ''' if not HAS_CLOUD: return False, 'config.gather_bootstrap_script is unavailable' ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) if 'Success' in ret and ret['Success']['Files updated']: return ret['Success']['Files updated'][0] def items(): ''' Return the complete config from the currently running minion process. This includes defaults for values not set in the config file. CLI Example: .. code-block:: bash salt '*' config.items ''' return __opts__
saltstack/salt
salt/modules/config.py
get
python
def get(key, default='', delimiter=':', merge=None, omit_opts=False, omit_pillar=False, omit_master=False, omit_grains=False): ''' .. versionadded: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master config. If the named value is not available, return the value specified by ``default``. If not specified, the default is an empty string. Values can also be retrieved from nested dictionaries. Assume the below data structure: .. code-block:: python {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key, in the sub-dictionary corresponding to the ``pkg`` key, the following command can be used: .. code-block:: bash salt myminion config.get pkg:apache The ``:`` (colon) is used to represent a nested dictionary level. .. versionchanged:: 2015.5.0 The ``delimiter`` argument was added, to allow delimiters other than ``:`` to be used. This function traverses these data stores in this order, returning the first match found: - Minion configuration - Minion's grains - Minion's pillar data - Master configuration (requires :conf_minion:`pillar_opts` to be set to ``True`` in Minion config file in order to work) This means that if there is a value that is going to be the same for the majority of minions, it can be configured in the Master config file, and then overridden using the grains, pillar, or Minion config file. Adding config options to the Master or Minion configuration file is easy: .. code-block:: yaml my-config-option: value cafe-menu: - egg and bacon - egg sausage and bacon - egg and spam - egg bacon and spam - egg bacon sausage and spam - spam bacon sausage and spam - spam egg spam spam bacon and spam - spam sausage spam spam bacon spam tomato and spam .. note:: Minion configuration options built into Salt (like those defined :ref:`here <configuration-salt-minion>`) will *always* be defined in the Minion configuration and thus *cannot be overridden by grains or pillar data*. However, additional (user-defined) configuration options (as in the above example) will not be in the Minion configuration by default and thus can be overridden using grains/pillar data by leaving the option out of the minion config file. **Arguments** delimiter .. versionadded:: 2015.5.0 Override the delimiter used to separate nested levels of a data structure. merge .. versionadded:: 2015.5.0 If passed, this parameter will change the behavior of the function so that, instead of traversing each data store above in order and returning the first match, the data stores are first merged together and then searched. The pillar data is merged into the master config data, then the grains are merged, followed by the Minion config data. The resulting data structure is then searched for a match. This allows for configurations to be more flexible. .. note:: The merging described above does not mean that grain data will end up in the Minion's pillar data, or pillar data will end up in the master config data, etc. The data is just combined for the purposes of searching an amalgam of the different data stores. The supported merge strategies are as follows: - **recurse** - If a key exists in both dictionaries, and the new value is not a dictionary, it is replaced. Otherwise, the sub-dictionaries are merged together into a single dictionary, recursively on down, following the same criteria. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'bar': 1, 'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} - **overwrite** - If a key exists in the top level of both dictionaries, the new value completely overwrites the old. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} CLI Example: .. code-block:: bash salt '*' config.get pkg:apache salt '*' config.get lxc.container_profile:centos merge=recurse ''' if merge is None: if not omit_opts: ret = salt.utils.data.traverse_dict_and_list( __opts__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_grains: ret = salt.utils.data.traverse_dict_and_list( __grains__, key, '_|-', delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_pillar: ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_master: ret = salt.utils.data.traverse_dict_and_list( __pillar__.get('master', {}), key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) ret = salt.utils.data.traverse_dict_and_list( DEFAULTS, key, '_|-', delimiter=delimiter) log.debug("key: %s, ret: %s", key, ret) if ret != '_|-': return sdb.sdb_get(ret, __opts__) else: if merge not in ('recurse', 'overwrite'): log.warning('Unsupported merge strategy \'%s\'. Falling back ' 'to \'recurse\'.', merge) merge = 'recurse' merge_lists = salt.config.master_config('/etc/salt/master').get('pillar_merge_lists') data = copy.copy(DEFAULTS) data = salt.utils.dictupdate.merge(data, __pillar__.get('master', {}), strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __pillar__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __grains__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __opts__, strategy=merge, merge_lists=merge_lists) ret = salt.utils.data.traverse_dict_and_list( data, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) return default
.. versionadded: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master config. If the named value is not available, return the value specified by ``default``. If not specified, the default is an empty string. Values can also be retrieved from nested dictionaries. Assume the below data structure: .. code-block:: python {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key, in the sub-dictionary corresponding to the ``pkg`` key, the following command can be used: .. code-block:: bash salt myminion config.get pkg:apache The ``:`` (colon) is used to represent a nested dictionary level. .. versionchanged:: 2015.5.0 The ``delimiter`` argument was added, to allow delimiters other than ``:`` to be used. This function traverses these data stores in this order, returning the first match found: - Minion configuration - Minion's grains - Minion's pillar data - Master configuration (requires :conf_minion:`pillar_opts` to be set to ``True`` in Minion config file in order to work) This means that if there is a value that is going to be the same for the majority of minions, it can be configured in the Master config file, and then overridden using the grains, pillar, or Minion config file. Adding config options to the Master or Minion configuration file is easy: .. code-block:: yaml my-config-option: value cafe-menu: - egg and bacon - egg sausage and bacon - egg and spam - egg bacon and spam - egg bacon sausage and spam - spam bacon sausage and spam - spam egg spam spam bacon and spam - spam sausage spam spam bacon spam tomato and spam .. note:: Minion configuration options built into Salt (like those defined :ref:`here <configuration-salt-minion>`) will *always* be defined in the Minion configuration and thus *cannot be overridden by grains or pillar data*. However, additional (user-defined) configuration options (as in the above example) will not be in the Minion configuration by default and thus can be overridden using grains/pillar data by leaving the option out of the minion config file. **Arguments** delimiter .. versionadded:: 2015.5.0 Override the delimiter used to separate nested levels of a data structure. merge .. versionadded:: 2015.5.0 If passed, this parameter will change the behavior of the function so that, instead of traversing each data store above in order and returning the first match, the data stores are first merged together and then searched. The pillar data is merged into the master config data, then the grains are merged, followed by the Minion config data. The resulting data structure is then searched for a match. This allows for configurations to be more flexible. .. note:: The merging described above does not mean that grain data will end up in the Minion's pillar data, or pillar data will end up in the master config data, etc. The data is just combined for the purposes of searching an amalgam of the different data stores. The supported merge strategies are as follows: - **recurse** - If a key exists in both dictionaries, and the new value is not a dictionary, it is replaced. Otherwise, the sub-dictionaries are merged together into a single dictionary, recursively on down, following the same criteria. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'bar': 1, 'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} - **overwrite** - If a key exists in the top level of both dictionaries, the new value completely overwrites the old. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} CLI Example: .. code-block:: bash salt '*' config.get pkg:apache salt '*' config.get lxc.container_profile:centos merge=recurse
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/config.py#L216-L422
[ "def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n", "def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n", "def sdb_get(uri, opts, utils=None):\n '''\n Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If\n the uri provided does not start with ``sdb://``, then it will be returned as-is.\n '''\n if not isinstance(uri, string_types) or not uri.startswith('sdb://'):\n return uri\n\n if utils is None:\n utils = salt.loader.utils(opts)\n\n sdlen = len('sdb://')\n indx = uri.find('/', sdlen)\n\n if (indx == -1) or not uri[(indx + 1):]:\n return uri\n\n profile = opts.get(uri[sdlen:indx], {})\n if not profile:\n profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})\n if 'driver' not in profile:\n return uri\n\n fun = '{0}.get'.format(profile['driver'])\n query = uri[indx+1:]\n\n loaded_db = salt.loader.sdb(opts, fun, utils=utils)\n return loaded_db[fun](query, profile=profile)\n" ]
# -*- coding: utf-8 -*- ''' Return config information ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import re import os import logging # Import salt libs import salt.config import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.platform try: # Gated for salt-ssh (salt.utils.cloud imports msgpack) import salt.utils.cloud HAS_CLOUD = True except ImportError: HAS_CLOUD = False import salt._compat import salt.syspaths as syspaths import salt.utils.sdb as sdb # Import 3rd-party libs from salt.ext import six if salt.utils.platform.is_windows(): _HOSTS_FILE = os.path.join( os.environ['SystemRoot'], 'System32', 'drivers', 'etc', 'hosts') else: _HOSTS_FILE = os.path.join(os.sep, 'etc', 'hosts') log = logging.getLogger(__name__) __proxyenabled__ = ['*'] # Set up the default values for all systems DEFAULTS = {'mongo.db': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': '', 'redis.db': '0', 'redis.host': 'salt', 'redis.port': 6379, 'test.foo': 'unconfigured', 'ca.cert_base_path': '/etc/pki', 'solr.cores': [], 'solr.host': 'localhost', 'solr.port': '8983', 'solr.baseurl': '/solr', 'solr.type': 'master', 'solr.request_timeout': None, 'solr.init_script': '/etc/rc.d/solr', 'solr.dih.import_options': {'clean': False, 'optimize': True, 'commit': True, 'verbose': False}, 'solr.backup_path': None, 'solr.num_backups': 1, 'poudriere.config': '/usr/local/etc/poudriere.conf', 'poudriere.config_dir': '/usr/local/etc/poudriere.d', 'ldap.uri': '', 'ldap.server': 'localhost', 'ldap.port': '389', 'ldap.tls': False, 'ldap.no_verify': False, 'ldap.anonymous': True, 'ldap.scope': 2, 'ldap.attrs': None, 'ldap.binddn': '', 'ldap.bindpw': '', 'hosts.file': _HOSTS_FILE, 'aliases.file': '/etc/aliases', 'virt': {'tunnel': False, 'images': os.path.join(syspaths.SRV_ROOT_DIR, 'salt-images')}, } def backup_mode(backup=''): ''' Return the backup mode CLI Example: .. code-block:: bash salt '*' config.backup_mode ''' if backup: return backup return option('backup_mode') def manage_mode(mode): ''' Return a mode value, normalized to a string CLI Example: .. code-block:: bash salt '*' config.manage_mode ''' # config.manage_mode should no longer be invoked from the __salt__ dunder # in Salt code, this function is only being left here for backwards # compatibility. return salt.utils.files.normalize_mode(mode) def valid_fileproto(uri): ''' Returns a boolean value based on whether or not the URI passed has a valid remote file protocol designation CLI Example: .. code-block:: bash salt '*' config.valid_fileproto salt://path/to/file ''' try: return bool(re.match('^(?:salt|https?|ftp)://', uri)) except Exception: return False def option( value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Pass in a generic option and receive the value that will be assigned CLI Example: .. code-block:: bash salt '*' config.option redis.host ''' if not omit_opts: if value in __opts__: return __opts__[value] if not omit_master: if value in __pillar__.get('master', {}): return __pillar__['master'][value] if not omit_pillar: if value in __pillar__: return __pillar__[value] if value in DEFAULTS: return DEFAULTS[value] return default def merge(value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Retrieves an option based on key, merging all matches. Same as ``option()`` except that it merges all matches, rather than taking the first match. CLI Example: .. code-block:: bash salt '*' config.merge schedule ''' ret = None if not omit_opts: if value in __opts__: ret = __opts__[value] if isinstance(ret, six.string_types): return ret if not omit_master: if value in __pillar__.get('master', {}): tmp = __pillar__['master'][value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if not omit_pillar: if value in __pillar__: tmp = __pillar__[value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if ret is None and value in DEFAULTS: return DEFAULTS[value] if ret is None: return default return ret def dot_vals(value): ''' Pass in a configuration value that should be preceded by the module name and a dot, this will return a list of all read key/value pairs CLI Example: .. code-block:: bash salt '*' config.dot_vals host ''' ret = {} for key, val in six.iteritems(__pillar__.get('master', {})): if key.startswith('{0}.'.format(value)): ret[key] = val for key, val in six.iteritems(__opts__): if key.startswith('{0}.'.format(value)): ret[key] = val return ret def gather_bootstrap_script(bootstrap=None): ''' Download the salt-bootstrap script, and return its location bootstrap URL of alternate bootstrap script CLI Example: .. code-block:: bash salt '*' config.gather_bootstrap_script ''' if not HAS_CLOUD: return False, 'config.gather_bootstrap_script is unavailable' ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) if 'Success' in ret and ret['Success']['Files updated']: return ret['Success']['Files updated'][0] def items(): ''' Return the complete config from the currently running minion process. This includes defaults for values not set in the config file. CLI Example: .. code-block:: bash salt '*' config.items ''' return __opts__
saltstack/salt
salt/modules/config.py
dot_vals
python
def dot_vals(value): ''' Pass in a configuration value that should be preceded by the module name and a dot, this will return a list of all read key/value pairs CLI Example: .. code-block:: bash salt '*' config.dot_vals host ''' ret = {} for key, val in six.iteritems(__pillar__.get('master', {})): if key.startswith('{0}.'.format(value)): ret[key] = val for key, val in six.iteritems(__opts__): if key.startswith('{0}.'.format(value)): ret[key] = val return ret
Pass in a configuration value that should be preceded by the module name and a dot, this will return a list of all read key/value pairs CLI Example: .. code-block:: bash salt '*' config.dot_vals host
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/config.py#L425-L443
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Return config information ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import re import os import logging # Import salt libs import salt.config import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.platform try: # Gated for salt-ssh (salt.utils.cloud imports msgpack) import salt.utils.cloud HAS_CLOUD = True except ImportError: HAS_CLOUD = False import salt._compat import salt.syspaths as syspaths import salt.utils.sdb as sdb # Import 3rd-party libs from salt.ext import six if salt.utils.platform.is_windows(): _HOSTS_FILE = os.path.join( os.environ['SystemRoot'], 'System32', 'drivers', 'etc', 'hosts') else: _HOSTS_FILE = os.path.join(os.sep, 'etc', 'hosts') log = logging.getLogger(__name__) __proxyenabled__ = ['*'] # Set up the default values for all systems DEFAULTS = {'mongo.db': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': '', 'redis.db': '0', 'redis.host': 'salt', 'redis.port': 6379, 'test.foo': 'unconfigured', 'ca.cert_base_path': '/etc/pki', 'solr.cores': [], 'solr.host': 'localhost', 'solr.port': '8983', 'solr.baseurl': '/solr', 'solr.type': 'master', 'solr.request_timeout': None, 'solr.init_script': '/etc/rc.d/solr', 'solr.dih.import_options': {'clean': False, 'optimize': True, 'commit': True, 'verbose': False}, 'solr.backup_path': None, 'solr.num_backups': 1, 'poudriere.config': '/usr/local/etc/poudriere.conf', 'poudriere.config_dir': '/usr/local/etc/poudriere.d', 'ldap.uri': '', 'ldap.server': 'localhost', 'ldap.port': '389', 'ldap.tls': False, 'ldap.no_verify': False, 'ldap.anonymous': True, 'ldap.scope': 2, 'ldap.attrs': None, 'ldap.binddn': '', 'ldap.bindpw': '', 'hosts.file': _HOSTS_FILE, 'aliases.file': '/etc/aliases', 'virt': {'tunnel': False, 'images': os.path.join(syspaths.SRV_ROOT_DIR, 'salt-images')}, } def backup_mode(backup=''): ''' Return the backup mode CLI Example: .. code-block:: bash salt '*' config.backup_mode ''' if backup: return backup return option('backup_mode') def manage_mode(mode): ''' Return a mode value, normalized to a string CLI Example: .. code-block:: bash salt '*' config.manage_mode ''' # config.manage_mode should no longer be invoked from the __salt__ dunder # in Salt code, this function is only being left here for backwards # compatibility. return salt.utils.files.normalize_mode(mode) def valid_fileproto(uri): ''' Returns a boolean value based on whether or not the URI passed has a valid remote file protocol designation CLI Example: .. code-block:: bash salt '*' config.valid_fileproto salt://path/to/file ''' try: return bool(re.match('^(?:salt|https?|ftp)://', uri)) except Exception: return False def option( value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Pass in a generic option and receive the value that will be assigned CLI Example: .. code-block:: bash salt '*' config.option redis.host ''' if not omit_opts: if value in __opts__: return __opts__[value] if not omit_master: if value in __pillar__.get('master', {}): return __pillar__['master'][value] if not omit_pillar: if value in __pillar__: return __pillar__[value] if value in DEFAULTS: return DEFAULTS[value] return default def merge(value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Retrieves an option based on key, merging all matches. Same as ``option()`` except that it merges all matches, rather than taking the first match. CLI Example: .. code-block:: bash salt '*' config.merge schedule ''' ret = None if not omit_opts: if value in __opts__: ret = __opts__[value] if isinstance(ret, six.string_types): return ret if not omit_master: if value in __pillar__.get('master', {}): tmp = __pillar__['master'][value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if not omit_pillar: if value in __pillar__: tmp = __pillar__[value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if ret is None and value in DEFAULTS: return DEFAULTS[value] if ret is None: return default return ret def get(key, default='', delimiter=':', merge=None, omit_opts=False, omit_pillar=False, omit_master=False, omit_grains=False): ''' .. versionadded: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master config. If the named value is not available, return the value specified by ``default``. If not specified, the default is an empty string. Values can also be retrieved from nested dictionaries. Assume the below data structure: .. code-block:: python {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key, in the sub-dictionary corresponding to the ``pkg`` key, the following command can be used: .. code-block:: bash salt myminion config.get pkg:apache The ``:`` (colon) is used to represent a nested dictionary level. .. versionchanged:: 2015.5.0 The ``delimiter`` argument was added, to allow delimiters other than ``:`` to be used. This function traverses these data stores in this order, returning the first match found: - Minion configuration - Minion's grains - Minion's pillar data - Master configuration (requires :conf_minion:`pillar_opts` to be set to ``True`` in Minion config file in order to work) This means that if there is a value that is going to be the same for the majority of minions, it can be configured in the Master config file, and then overridden using the grains, pillar, or Minion config file. Adding config options to the Master or Minion configuration file is easy: .. code-block:: yaml my-config-option: value cafe-menu: - egg and bacon - egg sausage and bacon - egg and spam - egg bacon and spam - egg bacon sausage and spam - spam bacon sausage and spam - spam egg spam spam bacon and spam - spam sausage spam spam bacon spam tomato and spam .. note:: Minion configuration options built into Salt (like those defined :ref:`here <configuration-salt-minion>`) will *always* be defined in the Minion configuration and thus *cannot be overridden by grains or pillar data*. However, additional (user-defined) configuration options (as in the above example) will not be in the Minion configuration by default and thus can be overridden using grains/pillar data by leaving the option out of the minion config file. **Arguments** delimiter .. versionadded:: 2015.5.0 Override the delimiter used to separate nested levels of a data structure. merge .. versionadded:: 2015.5.0 If passed, this parameter will change the behavior of the function so that, instead of traversing each data store above in order and returning the first match, the data stores are first merged together and then searched. The pillar data is merged into the master config data, then the grains are merged, followed by the Minion config data. The resulting data structure is then searched for a match. This allows for configurations to be more flexible. .. note:: The merging described above does not mean that grain data will end up in the Minion's pillar data, or pillar data will end up in the master config data, etc. The data is just combined for the purposes of searching an amalgam of the different data stores. The supported merge strategies are as follows: - **recurse** - If a key exists in both dictionaries, and the new value is not a dictionary, it is replaced. Otherwise, the sub-dictionaries are merged together into a single dictionary, recursively on down, following the same criteria. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'bar': 1, 'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} - **overwrite** - If a key exists in the top level of both dictionaries, the new value completely overwrites the old. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} CLI Example: .. code-block:: bash salt '*' config.get pkg:apache salt '*' config.get lxc.container_profile:centos merge=recurse ''' if merge is None: if not omit_opts: ret = salt.utils.data.traverse_dict_and_list( __opts__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_grains: ret = salt.utils.data.traverse_dict_and_list( __grains__, key, '_|-', delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_pillar: ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_master: ret = salt.utils.data.traverse_dict_and_list( __pillar__.get('master', {}), key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) ret = salt.utils.data.traverse_dict_and_list( DEFAULTS, key, '_|-', delimiter=delimiter) log.debug("key: %s, ret: %s", key, ret) if ret != '_|-': return sdb.sdb_get(ret, __opts__) else: if merge not in ('recurse', 'overwrite'): log.warning('Unsupported merge strategy \'%s\'. Falling back ' 'to \'recurse\'.', merge) merge = 'recurse' merge_lists = salt.config.master_config('/etc/salt/master').get('pillar_merge_lists') data = copy.copy(DEFAULTS) data = salt.utils.dictupdate.merge(data, __pillar__.get('master', {}), strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __pillar__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __grains__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __opts__, strategy=merge, merge_lists=merge_lists) ret = salt.utils.data.traverse_dict_and_list( data, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) return default def gather_bootstrap_script(bootstrap=None): ''' Download the salt-bootstrap script, and return its location bootstrap URL of alternate bootstrap script CLI Example: .. code-block:: bash salt '*' config.gather_bootstrap_script ''' if not HAS_CLOUD: return False, 'config.gather_bootstrap_script is unavailable' ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) if 'Success' in ret and ret['Success']['Files updated']: return ret['Success']['Files updated'][0] def items(): ''' Return the complete config from the currently running minion process. This includes defaults for values not set in the config file. CLI Example: .. code-block:: bash salt '*' config.items ''' return __opts__
saltstack/salt
salt/modules/config.py
gather_bootstrap_script
python
def gather_bootstrap_script(bootstrap=None): ''' Download the salt-bootstrap script, and return its location bootstrap URL of alternate bootstrap script CLI Example: .. code-block:: bash salt '*' config.gather_bootstrap_script ''' if not HAS_CLOUD: return False, 'config.gather_bootstrap_script is unavailable' ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) if 'Success' in ret and ret['Success']['Files updated']: return ret['Success']['Files updated'][0]
Download the salt-bootstrap script, and return its location bootstrap URL of alternate bootstrap script CLI Example: .. code-block:: bash salt '*' config.gather_bootstrap_script
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/config.py#L446-L463
[ "def update_bootstrap(config, url=None):\n '''\n Update the salt-bootstrap script\n\n url can be one of:\n\n - The URL to fetch the bootstrap script from\n - The absolute path to the bootstrap\n - The content of the bootstrap script\n '''\n default_url = config.get('bootstrap_script_url',\n 'https://bootstrap.saltstack.com')\n if not url:\n url = default_url\n if not url:\n raise ValueError('Cant get any source to update')\n if url.startswith('http') or '://' in url:\n log.debug('Updating the bootstrap-salt.sh script to latest stable')\n try:\n import requests\n except ImportError:\n return {'error': (\n 'Updating the bootstrap-salt.sh script requires the '\n 'Python requests library to be installed'\n )}\n req = requests.get(url)\n if req.status_code != 200:\n return {'error': (\n 'Failed to download the latest stable version of the '\n 'bootstrap-salt.sh script from {0}. HTTP error: '\n '{1}'.format(\n url, req.status_code\n )\n )}\n script_content = req.text\n if url == default_url:\n script_name = 'bootstrap-salt.sh'\n else:\n script_name = os.path.basename(url)\n elif os.path.exists(url):\n with salt.utils.files.fopen(url) as fic:\n script_content = salt.utils.stringutils.to_unicode(fic.read())\n script_name = os.path.basename(url)\n # in last case, assuming we got a script content\n else:\n script_content = url\n script_name = '{0}.sh'.format(\n hashlib.sha1(script_content).hexdigest()\n )\n\n if not script_content:\n raise ValueError('No content in bootstrap script !')\n\n # Get the path to the built-in deploy scripts directory\n builtin_deploy_dir = os.path.join(\n os.path.dirname(__file__),\n 'deploy'\n )\n\n # Compute the search path from the current loaded opts conf_file\n # value\n deploy_d_from_conf_file = os.path.join(\n os.path.dirname(config['conf_file']),\n 'cloud.deploy.d'\n )\n\n # Compute the search path using the install time defined\n # syspaths.CONF_DIR\n deploy_d_from_syspaths = os.path.join(\n config['config_dir'],\n 'cloud.deploy.d'\n )\n\n # Get a copy of any defined search paths, flagging them not to\n # create parent\n deploy_scripts_search_paths = []\n for entry in config.get('deploy_scripts_search_path', []):\n if entry.startswith(builtin_deploy_dir):\n # We won't write the updated script to the built-in deploy\n # directory\n continue\n\n if entry in (deploy_d_from_conf_file, deploy_d_from_syspaths):\n # Allow parent directories to be made\n deploy_scripts_search_paths.append((entry, True))\n else:\n deploy_scripts_search_paths.append((entry, False))\n\n # In case the user is not using defaults and the computed\n # 'cloud.deploy.d' from conf_file and syspaths is not included, add\n # them\n if deploy_d_from_conf_file not in deploy_scripts_search_paths:\n deploy_scripts_search_paths.append(\n (deploy_d_from_conf_file, True)\n )\n if deploy_d_from_syspaths not in deploy_scripts_search_paths:\n deploy_scripts_search_paths.append(\n (deploy_d_from_syspaths, True)\n )\n\n finished = []\n finished_full = []\n for entry, makedirs in deploy_scripts_search_paths:\n # This handles duplicate entries, which are likely to appear\n if entry in finished:\n continue\n else:\n finished.append(entry)\n\n if makedirs and not os.path.isdir(entry):\n try:\n os.makedirs(entry)\n except (OSError, IOError) as err:\n log.info('Failed to create directory \\'%s\\'', entry)\n continue\n\n if not is_writeable(entry):\n log.debug('The \\'%s\\' is not writeable. Continuing...', entry)\n continue\n\n deploy_path = os.path.join(entry, script_name)\n try:\n finished_full.append(deploy_path)\n with salt.utils.files.fopen(deploy_path, 'w') as fp_:\n fp_.write(salt.utils.stringutils.to_str(script_content))\n except (OSError, IOError) as err:\n log.debug('Failed to write the updated script: %s', err)\n continue\n\n return {'Success': {'Files updated': finished_full}}\n" ]
# -*- coding: utf-8 -*- ''' Return config information ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import re import os import logging # Import salt libs import salt.config import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.platform try: # Gated for salt-ssh (salt.utils.cloud imports msgpack) import salt.utils.cloud HAS_CLOUD = True except ImportError: HAS_CLOUD = False import salt._compat import salt.syspaths as syspaths import salt.utils.sdb as sdb # Import 3rd-party libs from salt.ext import six if salt.utils.platform.is_windows(): _HOSTS_FILE = os.path.join( os.environ['SystemRoot'], 'System32', 'drivers', 'etc', 'hosts') else: _HOSTS_FILE = os.path.join(os.sep, 'etc', 'hosts') log = logging.getLogger(__name__) __proxyenabled__ = ['*'] # Set up the default values for all systems DEFAULTS = {'mongo.db': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': '', 'redis.db': '0', 'redis.host': 'salt', 'redis.port': 6379, 'test.foo': 'unconfigured', 'ca.cert_base_path': '/etc/pki', 'solr.cores': [], 'solr.host': 'localhost', 'solr.port': '8983', 'solr.baseurl': '/solr', 'solr.type': 'master', 'solr.request_timeout': None, 'solr.init_script': '/etc/rc.d/solr', 'solr.dih.import_options': {'clean': False, 'optimize': True, 'commit': True, 'verbose': False}, 'solr.backup_path': None, 'solr.num_backups': 1, 'poudriere.config': '/usr/local/etc/poudriere.conf', 'poudriere.config_dir': '/usr/local/etc/poudriere.d', 'ldap.uri': '', 'ldap.server': 'localhost', 'ldap.port': '389', 'ldap.tls': False, 'ldap.no_verify': False, 'ldap.anonymous': True, 'ldap.scope': 2, 'ldap.attrs': None, 'ldap.binddn': '', 'ldap.bindpw': '', 'hosts.file': _HOSTS_FILE, 'aliases.file': '/etc/aliases', 'virt': {'tunnel': False, 'images': os.path.join(syspaths.SRV_ROOT_DIR, 'salt-images')}, } def backup_mode(backup=''): ''' Return the backup mode CLI Example: .. code-block:: bash salt '*' config.backup_mode ''' if backup: return backup return option('backup_mode') def manage_mode(mode): ''' Return a mode value, normalized to a string CLI Example: .. code-block:: bash salt '*' config.manage_mode ''' # config.manage_mode should no longer be invoked from the __salt__ dunder # in Salt code, this function is only being left here for backwards # compatibility. return salt.utils.files.normalize_mode(mode) def valid_fileproto(uri): ''' Returns a boolean value based on whether or not the URI passed has a valid remote file protocol designation CLI Example: .. code-block:: bash salt '*' config.valid_fileproto salt://path/to/file ''' try: return bool(re.match('^(?:salt|https?|ftp)://', uri)) except Exception: return False def option( value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Pass in a generic option and receive the value that will be assigned CLI Example: .. code-block:: bash salt '*' config.option redis.host ''' if not omit_opts: if value in __opts__: return __opts__[value] if not omit_master: if value in __pillar__.get('master', {}): return __pillar__['master'][value] if not omit_pillar: if value in __pillar__: return __pillar__[value] if value in DEFAULTS: return DEFAULTS[value] return default def merge(value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Retrieves an option based on key, merging all matches. Same as ``option()`` except that it merges all matches, rather than taking the first match. CLI Example: .. code-block:: bash salt '*' config.merge schedule ''' ret = None if not omit_opts: if value in __opts__: ret = __opts__[value] if isinstance(ret, six.string_types): return ret if not omit_master: if value in __pillar__.get('master', {}): tmp = __pillar__['master'][value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if not omit_pillar: if value in __pillar__: tmp = __pillar__[value] if ret is None: ret = tmp if isinstance(ret, six.string_types): return ret elif isinstance(ret, dict) and isinstance(tmp, dict): tmp.update(ret) ret = tmp elif isinstance(ret, (list, tuple)) and isinstance(tmp, (list, tuple)): ret = list(ret) + list(tmp) if ret is None and value in DEFAULTS: return DEFAULTS[value] if ret is None: return default return ret def get(key, default='', delimiter=':', merge=None, omit_opts=False, omit_pillar=False, omit_master=False, omit_grains=False): ''' .. versionadded: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master config. If the named value is not available, return the value specified by ``default``. If not specified, the default is an empty string. Values can also be retrieved from nested dictionaries. Assume the below data structure: .. code-block:: python {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the ``apache`` key, in the sub-dictionary corresponding to the ``pkg`` key, the following command can be used: .. code-block:: bash salt myminion config.get pkg:apache The ``:`` (colon) is used to represent a nested dictionary level. .. versionchanged:: 2015.5.0 The ``delimiter`` argument was added, to allow delimiters other than ``:`` to be used. This function traverses these data stores in this order, returning the first match found: - Minion configuration - Minion's grains - Minion's pillar data - Master configuration (requires :conf_minion:`pillar_opts` to be set to ``True`` in Minion config file in order to work) This means that if there is a value that is going to be the same for the majority of minions, it can be configured in the Master config file, and then overridden using the grains, pillar, or Minion config file. Adding config options to the Master or Minion configuration file is easy: .. code-block:: yaml my-config-option: value cafe-menu: - egg and bacon - egg sausage and bacon - egg and spam - egg bacon and spam - egg bacon sausage and spam - spam bacon sausage and spam - spam egg spam spam bacon and spam - spam sausage spam spam bacon spam tomato and spam .. note:: Minion configuration options built into Salt (like those defined :ref:`here <configuration-salt-minion>`) will *always* be defined in the Minion configuration and thus *cannot be overridden by grains or pillar data*. However, additional (user-defined) configuration options (as in the above example) will not be in the Minion configuration by default and thus can be overridden using grains/pillar data by leaving the option out of the minion config file. **Arguments** delimiter .. versionadded:: 2015.5.0 Override the delimiter used to separate nested levels of a data structure. merge .. versionadded:: 2015.5.0 If passed, this parameter will change the behavior of the function so that, instead of traversing each data store above in order and returning the first match, the data stores are first merged together and then searched. The pillar data is merged into the master config data, then the grains are merged, followed by the Minion config data. The resulting data structure is then searched for a match. This allows for configurations to be more flexible. .. note:: The merging described above does not mean that grain data will end up in the Minion's pillar data, or pillar data will end up in the master config data, etc. The data is just combined for the purposes of searching an amalgam of the different data stores. The supported merge strategies are as follows: - **recurse** - If a key exists in both dictionaries, and the new value is not a dictionary, it is replaced. Otherwise, the sub-dictionaries are merged together into a single dictionary, recursively on down, following the same criteria. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'bar': 1, 'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} - **overwrite** - If a key exists in the top level of both dictionaries, the new value completely overwrites the old. For example: .. code-block:: python >>> dict1 = {'foo': {'bar': 1, 'qux': True}, 'hosts': ['a', 'b', 'c'], 'only_x': None} >>> dict2 = {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_y': None} >>> merged {'foo': {'baz': 2, 'qux': False}, 'hosts': ['d', 'e', 'f'], 'only_dict1': None, 'only_dict2': None} CLI Example: .. code-block:: bash salt '*' config.get pkg:apache salt '*' config.get lxc.container_profile:centos merge=recurse ''' if merge is None: if not omit_opts: ret = salt.utils.data.traverse_dict_and_list( __opts__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_grains: ret = salt.utils.data.traverse_dict_and_list( __grains__, key, '_|-', delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_pillar: ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) if not omit_master: ret = salt.utils.data.traverse_dict_and_list( __pillar__.get('master', {}), key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) ret = salt.utils.data.traverse_dict_and_list( DEFAULTS, key, '_|-', delimiter=delimiter) log.debug("key: %s, ret: %s", key, ret) if ret != '_|-': return sdb.sdb_get(ret, __opts__) else: if merge not in ('recurse', 'overwrite'): log.warning('Unsupported merge strategy \'%s\'. Falling back ' 'to \'recurse\'.', merge) merge = 'recurse' merge_lists = salt.config.master_config('/etc/salt/master').get('pillar_merge_lists') data = copy.copy(DEFAULTS) data = salt.utils.dictupdate.merge(data, __pillar__.get('master', {}), strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __pillar__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __grains__, strategy=merge, merge_lists=merge_lists) data = salt.utils.dictupdate.merge(data, __opts__, strategy=merge, merge_lists=merge_lists) ret = salt.utils.data.traverse_dict_and_list( data, key, '_|-', delimiter=delimiter) if ret != '_|-': return sdb.sdb_get(ret, __opts__) return default def dot_vals(value): ''' Pass in a configuration value that should be preceded by the module name and a dot, this will return a list of all read key/value pairs CLI Example: .. code-block:: bash salt '*' config.dot_vals host ''' ret = {} for key, val in six.iteritems(__pillar__.get('master', {})): if key.startswith('{0}.'.format(value)): ret[key] = val for key, val in six.iteritems(__opts__): if key.startswith('{0}.'.format(value)): ret[key] = val return ret def items(): ''' Return the complete config from the currently running minion process. This includes defaults for values not set in the config file. CLI Example: .. code-block:: bash salt '*' config.items ''' return __opts__
saltstack/salt
salt/states/panos.py
_build_members
python
def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members)
Builds a member formatted string for XML operation.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L101-L116
null
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
_edit_config
python
def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response)
Sends an edit request to the device.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L134-L146
[ "def _validate_response(response):\n '''\n Validates a response from a Palo Alto device. Used to verify success of commands.\n\n '''\n if not response:\n return False, 'Unable to validate response from device.'\n elif 'msg' in response:\n if 'line' in response['msg']:\n if response['msg']['line'] == 'already at the top':\n return True, response\n elif response['msg']['line'] == 'already at the bottom':\n return True, response\n else:\n return False, response\n elif response['msg'] == 'command succeeded':\n return True, response\n else:\n return False, response\n elif 'status' in response:\n if response['status'] == \"success\":\n return True, response\n else:\n return False, response\n else:\n return False, response\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
_move_after
python
def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response)
Moves an xpath to the after of its section.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L163-L176
[ "def _validate_response(response):\n '''\n Validates a response from a Palo Alto device. Used to verify success of commands.\n\n '''\n if not response:\n return False, 'Unable to validate response from device.'\n elif 'msg' in response:\n if 'line' in response['msg']:\n if response['msg']['line'] == 'already at the top':\n return True, response\n elif response['msg']['line'] == 'already at the bottom':\n return True, response\n else:\n return False, response\n elif response['msg'] == 'command succeeded':\n return True, response\n else:\n return False, response\n elif 'status' in response:\n if response['status'] == \"success\":\n return True, response\n else:\n return False, response\n else:\n return False, response\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
_move_before
python
def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response)
Moves an xpath to the bottom of its section.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L179-L192
[ "def _validate_response(response):\n '''\n Validates a response from a Palo Alto device. Used to verify success of commands.\n\n '''\n if not response:\n return False, 'Unable to validate response from device.'\n elif 'msg' in response:\n if 'line' in response['msg']:\n if response['msg']['line'] == 'already at the top':\n return True, response\n elif response['msg']['line'] == 'already at the bottom':\n return True, response\n else:\n return False, response\n elif response['msg'] == 'command succeeded':\n return True, response\n else:\n return False, response\n elif 'status' in response:\n if response['status'] == \"success\":\n return True, response\n else:\n return False, response\n else:\n return False, response\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
_set_config
python
def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response)
Sends a set request to the device.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L225-L237
[ "def _validate_response(response):\n '''\n Validates a response from a Palo Alto device. Used to verify success of commands.\n\n '''\n if not response:\n return False, 'Unable to validate response from device.'\n elif 'msg' in response:\n if 'line' in response['msg']:\n if response['msg']['line'] == 'already at the top':\n return True, response\n elif response['msg']['line'] == 'already at the bottom':\n return True, response\n else:\n return False, response\n elif response['msg'] == 'command succeeded':\n return True, response\n else:\n return False, response\n elif 'status' in response:\n if response['status'] == \"success\":\n return True, response\n else:\n return False, response\n else:\n return False, response\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
_validate_response
python
def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response
Validates a response from a Palo Alto device. Used to verify success of commands.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L240-L265
null
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
add_config_lock
python
def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret
Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L268-L289
[ "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
address_exists
python
def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L292-L424
[ "def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n", "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n", "def _edit_config(xpath, element):\n '''\n Sends an edit request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'edit',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
commit_config
python
def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L589-L610
[ "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
delete_config
python
def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L613-L660
[ "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n", "def _validate_response(response):\n '''\n Validates a response from a Palo Alto device. Used to verify success of commands.\n\n '''\n if not response:\n return False, 'Unable to validate response from device.'\n elif 'msg' in response:\n if 'line' in response['msg']:\n if response['msg']['line'] == 'already at the top':\n return True, response\n elif response['msg']['line'] == 'already at the bottom':\n return True, response\n else:\n return False, response\n elif response['msg'] == 'command succeeded':\n return True, response\n else:\n return False, response\n elif 'status' in response:\n if response['status'] == \"success\":\n return True, response\n else:\n return False, response\n else:\n return False, response\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
download_software
python
def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret
Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L663-L733
[ "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
edit_config
python
def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret
Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L736-L815
[ "def to_dict(xmltree, attr=False):\n '''\n Convert an XML tree into a dict. The tree that is passed in must be an\n ElementTree object.\n Args:\n xmltree: An ElementTree object.\n attr: If true, attributes will be parsed. If false, they will be ignored.\n\n '''\n if attr:\n return _to_full_dict(xmltree)\n else:\n return _to_dict(xmltree)\n", "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n", "def _edit_config(xpath, element):\n '''\n Sends an edit request to the device.\n\n '''\n query = {'type': 'config',\n 'action': 'edit',\n 'xpath': xpath,\n 'element': element}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
saltstack/salt
salt/states/panos.py
move_config
python
def move_config(name, xpath=None, where=None, dst=None, commit=False): ''' Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == 'after': result, msg = _move_after(xpath, dst) elif where == 'before': result, msg = _move_before(xpath, dst) elif where == 'top': result, msg = _move_top(xpath) elif where == 'bottom': result, msg = _move_bottom(xpath) ret.update({ 'result': result, 'comment': msg }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret
Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to move. where(str): The type of move to execute. Valid options are after, before, top, bottom. The after and before options will require the dst option to specify the destination of the action. The top action will move the XPATH to the top of its structure. The botoom action will move the XPATH to the bottom of its structure. dst(str): Optional. Specifies the destination to utilize for a move action. This is ignored for the top or bottom action. commit(bool): If true the firewall will commit the changes, if false do not commit changes. If the operation is not successful, it will not commit. SLS Example: .. code-block:: yaml panos/moveruletop: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: True panos/moveruleafter: panos.move_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: after - dst: rule2 - commit: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L818-L888
[ "def _default_ret(name):\n '''\n Set the default response values.\n\n '''\n ret = {\n 'name': name,\n 'changes': {},\n 'commit': None,\n 'result': False,\n 'comment': ''\n }\n return ret\n", "def _move_after(xpath, target):\n '''\n Moves an xpath to the after of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'after',\n 'dst': target}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n", "def _move_before(xpath, target):\n '''\n Moves an xpath to the bottom of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'before',\n 'dst': target}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n", "def _move_bottom(xpath):\n '''\n Moves an xpath to the bottom of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'bottom'}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n", "def _move_top(xpath):\n '''\n Moves an xpath to the top of its section.\n\n '''\n query = {'type': 'config',\n 'action': 'move',\n 'xpath': xpath,\n 'where': 'top'}\n\n response = __proxy__['panos.call'](query)\n\n return _validate_response(response)\n" ]
# -*- coding: utf-8 -*- ''' A state module to manage Palo Alto network devices. :codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>`` :maturity: new :depends: none :platform: unix About ===== This state module was designed to handle connections to a Palo Alto based firewall. This module relies on the Palo Alto proxy module to interface with the devices. This state module is designed to give extreme flexibility in the control over XPATH values on the PANOS device. It exposes the core XML API commands and allows state modules to chain complex XPATH commands. Below is an example of how to construct a security rule and move to the top of the policy. This will take a config lock to prevent execution during the operation, then remove the lock. After the XPATH has been deployed, it will commit to the device. .. code-block:: yaml panos/takelock: panos.add_config_lock panos/service_tcp_22: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/service - value: <entry name='tcp-22'><protocol><tcp><port>22</port></tcp></protocol></entry> - commit: False panos/create_rule1: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules - value: ' <entry name="rule1"> <from><member>trust</member></from> <to><member>untrust</member></to> <source><member>10.0.0.1</member></source> <destination><member>10.0.1.1</member></destination> <service><member>tcp-22</member></service> <application><member>any</member></application> <action>allow</action> <disabled>no</disabled> </entry>' - commit: False panos/moveruletop: panos.move_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - where: top - commit: False panos/removelock: panos.remove_config_lock panos/commit: panos.commit Version Specific Configurations =============================== Palo Alto devices running different versions will have different supported features and different command structures. In order to account for this, the proxy module can be leveraged to check if the panos device is at a specific revision level. The proxy['panos.is_required_version'] method will check if a panos device is currently running a version equal or greater than the passed version. For example, proxy['panos.is_required_version']('7.0.0') would match both 7.1.0 and 8.0.0. .. code-block:: jinja {% if proxy['panos.is_required_version']('8.0.0') %} panos/deviceconfig/system/motd-and-banner: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/motd-and-banner - value: | <banner-header>BANNER TEXT</banner-header> <banner-header-color>color2</banner-header-color> <banner-header-text-color>color18</banner-header-text-color> <banner-header-footer-match>yes</banner-header-footer-match> - commit: False {% endif %} .. seealso:: :py:mod:`Palo Alto Proxy Module <salt.proxy.panos>` ''' # Import Python Libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.xmlutil as xml from salt._compat import ElementTree as ET log = logging.getLogger(__name__) def __virtual__(): return 'panos.commit' in __salt__ def _build_members(members, anycheck=False): ''' Builds a member formatted string for XML operation. ''' if isinstance(members, list): # This check will strip down members to a single any statement if anycheck and 'any' in members: return "<member>any</member>" response = "" for m in members: response += "<member>{0}</member>".format(m) return response else: return "<member>{0}</member>".format(members) def _default_ret(name): ''' Set the default response values. ''' ret = { 'name': name, 'changes': {}, 'commit': None, 'result': False, 'comment': '' } return ret def _edit_config(xpath, element): ''' Sends an edit request to the device. ''' query = {'type': 'config', 'action': 'edit', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _get_config(xpath): ''' Retrieves an xpath from the device. ''' query = {'type': 'config', 'action': 'get', 'xpath': xpath} response = __proxy__['panos.call'](query) return response def _move_after(xpath, target): ''' Moves an xpath to the after of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'after', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_before(xpath, target): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'before', 'dst': target} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_bottom(xpath): ''' Moves an xpath to the bottom of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'bottom'} response = __proxy__['panos.call'](query) return _validate_response(response) def _move_top(xpath): ''' Moves an xpath to the top of its section. ''' query = {'type': 'config', 'action': 'move', 'xpath': xpath, 'where': 'top'} response = __proxy__['panos.call'](query) return _validate_response(response) def _set_config(xpath, element): ''' Sends a set request to the device. ''' query = {'type': 'config', 'action': 'set', 'xpath': xpath, 'element': element} response = __proxy__['panos.call'](query) return _validate_response(response) def _validate_response(response): ''' Validates a response from a Palo Alto device. Used to verify success of commands. ''' if not response: return False, 'Unable to validate response from device.' elif 'msg' in response: if 'line' in response['msg']: if response['msg']['line'] == 'already at the top': return True, response elif response['msg']['line'] == 'already at the bottom': return True, response else: return False, response elif response['msg'] == 'command succeeded': return True, response else: return False, response elif 'status' in response: if response['status'] == "success": return True, response else: return False, response else: return False, response def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.add_config_lock'](), 'result': True }) return ret def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value if the following order: ip-netmask, ip-range, fqdn. For proper execution, only specify a single address type. name: The name of the module function to execute. addressname(str): The name of the address object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. ipnetmask(str): The IPv4 or IPv6 address or IP address range using the format ip_address/mask or ip_address where the mask is the number of significant binary digits used for the network portion of the address. Ideally, for IPv6, you specify only the network portion, not the host portion. iprange(str): A range of addresses using the format ip_address–ip_address where both addresses can be IPv4 or both can be IPv6. fqdn(str): A fully qualified domain name format. The FQDN initially resolves at commit time. Entries are subsequently refreshed when the firewall performs a check every 30 minutes; all changes in the IP address for the entries are picked up at the refresh cycle. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address/h-10.10.10.10: panos.address_exists: - addressname: h-10.10.10.10 - vsys: 1 - ipnetmask: 10.10.10.10 - commit: False panos/address/10.0.0.1-10.0.0.50: panos.address_exists: - addressname: r-10.0.0.1-10.0.0.50 - vsys: 1 - iprange: 10.0.0.1-10.0.0.50 - commit: False panos/address/foo.bar.com: panos.address_exists: - addressname: foo.bar.com - vsys: 1 - fqdn: foo.bar.com - description: My fqdn object - commit: False ''' ret = _default_ret(name) if not addressname: ret.update({'comment': "The service name field must be provided."}) return ret # Check if address object currently exists address = __salt__['panos.get_address'](addressname, vsys)['result'] if address and 'entry' in address: address = address['entry'] else: address = {} element = "" # Verify the arguments if ipnetmask: element = "<ip-netmask>{0}</ip-netmask>".format(ipnetmask) elif iprange: element = "<ip-range>{0}</ip-range>".format(iprange) elif fqdn: element = "<fqdn>{0}</fqdn>".format(fqdn) else: ret.update({'comment': "A valid address type must be specified."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(addressname, element) new_address = xml.to_dict(ET.fromstring(full_element), True) if address == new_address: ret.update({ 'comment': 'Address object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address/" \ "entry[@name=\'{1}\']".format(vsys, addressname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': address, 'after': new_address}, 'commit': __salt__['panos.commit'](), 'comment': 'Address object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': address, 'after': new_address}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def address_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that an address group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the address group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the address group. These must be valid address objects or address groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/address-group/my-group: panos.address_group_exists: - groupname: my-group - vsys: 1 - members: - my-address-object - my-other-address-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if address group object currently exists group = __salt__['panos.get_address_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<static>{0}</static>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Address group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/address-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Address group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Address group object successfully configured.', 'result': True }) return ret def clone_config(name, xpath=None, newname=None, commit=False): ''' Clone a specific XPATH and set it to a new name. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to clone. newname(str): The new name of the XPATH clone. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/clonerule: panos.clone_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules&from=/config/devices/ entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='rule1'] - value: rule2 - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'clone', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def commit_config(name): ''' Commits the candidate configuration to the running configuration. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/commit: panos.commit_config ''' ret = _default_ret(name) ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def delete_config(name, xpath=None, commit=False): ''' Deletes a Palo Alto XPATH to a specific value. Use the xpath parameter to specify the location of the object to be deleted. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/deletegroup: panos.delete_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - commit: True ''' ret = _default_ret(name) if not xpath: return ret query = {'type': 'config', 'action': 'delete', 'xpath': xpath} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be synched to its peer. check(bool): If true, the PANOS device will first attempt to pull the most recent software inventory list from Palo Alto. SLS Example: .. code-block:: yaml panos/version8.0.0: panos.download_software: - version: 8.0.0 - synch: False - check: True ''' ret = _default_ret(name) if check is True: __salt__['panos.check_software']() versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'comment': 'Software version is not found in the local software list.', 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'comment': 'Software version is already downloaded.', 'result': True }) return ret ret.update({ 'changes': __salt__['panos.download_software_version'](version=version, synch=synch) }) versions = __salt__['panos.get_software_info']()['result'] if 'sw-updates' not in versions \ or 'versions' not in versions['sw-updates'] \ or 'entry' not in versions['sw-updates']['versions']: ret.update({ 'result': False }) return ret for entry in versions['sw-updates']['versions']['entry']: if entry['version'] == version and entry['downloaded'] == "yes": ret.update({ 'result': True }) return ret return ret def edit_config(name, xpath=None, value=None, commit=False): ''' Edits a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can replace an existing object hierarchy at a specified location in the configuration with a new value. Use the xpath parameter to specify the location of the object, including the node to be replaced. This is the recommended state to enforce configurations on a xpath. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to edit. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/addressgroup: panos.edit_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address-group/entry[@name='test'] - value: <static><entry name='test'><member>abc</member><member>xyz</member></entry></static> - commit: True ''' ret = _default_ret(name) # Verify if the current XPATH is equal to the specified value. # If we are equal, no changes required. xpath_split = xpath.split("/") # Retrieve the head of the xpath for validation. if xpath_split: head = xpath_split[-1] if "[" in head: head = head.split("[")[0] current_element = __salt__['panos.get_xpath'](xpath)['result'] if head and current_element and head in current_element: current_element = current_element[head] else: current_element = {} new_element = xml.to_dict(ET.fromstring(value), True) if current_element == new_element: ret.update({ 'comment': 'XPATH is already equal to the specified value.', 'result': True }) return ret result, msg = _edit_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'changes': {'before': current_element, 'after': new_element}, 'result': True }) return ret def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __salt__['panos.remove_config_lock'](), 'result': True }) return ret def rename_config(name, xpath=None, newname=None, commit=False): ''' Rename a Palo Alto XPATH to a specific value. This will always rename the value even if a change is not needed. name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. newname(str): The new name of the XPATH value. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/renamegroup: panos.rename_config: - xpath: /config/devices/entry/vsys/entry[@name='vsys1']/address/entry[@name='old_address'] - value: new_address - commit: True ''' ret = _default_ret(name) if not xpath: return ret if not newname: return ret query = {'type': 'config', 'action': 'rename', 'xpath': xpath, 'newname': newname} result, response = _validate_response(__proxy__['panos.call'](query)) ret.update({ 'changes': response, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret def security_rule_exists(name, rulename=None, vsys='1', action=None, disabled=None, sourcezone=None, destinationzone=None, source=None, destination=None, application=None, service=None, description=None, logsetting=None, logstart=None, logend=None, negatesource=None, negatedestination=None, profilegroup=None, datafilter=None, fileblock=None, spyware=None, urlfilter=None, virus=None, vulnerability=None, wildfire=None, move=None, movetarget=None, commit=False): ''' Ensures that a security rule exists on the device. Also, ensure that all configurations are set appropriately. This method will create the rule if it does not exist. If the rule does exist, it will ensure that the configurations are set appropriately. If the rule does not exist and is created, any value that is not provided will be provided as the default. The action, to, from, source, destination, application, and service fields are mandatory and must be provided. This will enforce the exact match of the rule. For example, if the rule is currently configured with the log-end option, but this option is not specified in the state method, it will be removed and reset to the system default. It is strongly recommended to specify all options to ensure proper operation. When defining the profile group settings, the device can only support either a profile group or individual settings. If both are specified, the profile group will be preferred and the individual settings are ignored. If neither are specified, the value will be set to system default of none. name: The name of the module function to execute. rulename(str): The name of the security rule. The name is case-sensitive and can have up to 31 characters, which can be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. action(str): The action that the security rule will enforce. Valid options are: allow, deny, drop, reset-client, reset-server, reset-both. disabled(bool): Controls if the rule is disabled. Set 'True' to disable and 'False' to enable. sourcezone(str, list): The source zone(s). The value 'any' will match all zones. destinationzone(str, list): The destination zone(s). The value 'any' will match all zones. source(str, list): The source address(es). The value 'any' will match all addresses. destination(str, list): The destination address(es). The value 'any' will match all addresses. application(str, list): The application(s) matched. The value 'any' will match all applications. service(str, list): The service(s) matched. The value 'any' will match all services. The value 'application-default' will match based upon the application defined ports. description(str): A description for the policy (up to 255 characters). logsetting(str): The name of a valid log forwarding profile. logstart(bool): Generates a traffic log entry for the start of a session (disabled by default). logend(bool): Generates a traffic log entry for the end of a session (enabled by default). negatesource(bool): Match all but the specified source addresses. negatedestination(bool): Match all but the specified destination addresses. profilegroup(str): A valid profile group name. datafilter(str): A valid data filter profile name. Ignored with the profilegroup option set. fileblock(str): A valid file blocking profile name. Ignored with the profilegroup option set. spyware(str): A valid spyware profile name. Ignored with the profilegroup option set. urlfilter(str): A valid URL filtering profile name. Ignored with the profilegroup option set. virus(str): A valid virus profile name. Ignored with the profilegroup option set. vulnerability(str): A valid vulnerability profile name. Ignored with the profilegroup option set. wildfire(str): A valid vulnerability profile name. Ignored with the profilegroup option set. move(str): An optional argument that ensure the rule is moved to a specific location. Valid options are 'top', 'bottom', 'before', or 'after'. The 'before' and 'after' options require the use of the 'movetarget' argument to define the location of the move request. movetarget(str): An optional argument that defines the target of the move operation if the move argument is set to 'before' or 'after'. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: True - negatesource: False - negatedestination: False - profilegroup: myprofilegroup - move: top - commit: False panos/rulebase/security/rule01: panos.security_rule_exists: - rulename: rule01 - vsys: 1 - action: allow - disabled: False - sourcezone: untrust - destinationzone: trust - source: - 10.10.10.0/24 - 1.1.1.1 - destination: - 2.2.2.2-2.2.2.4 - application: - any - service: - tcp-25 - description: My test security rule - logsetting: logprofile - logstart: False - logend: False - datafilter: foobar - fileblock: foobar - spyware: foobar - urlfilter: foobar - virus: foobar - vulnerability: foobar - wildfire: foobar - move: after - movetarget: rule02 - commit: False ''' ret = _default_ret(name) if not rulename: return ret # Check if rule currently exists rule = __salt__['panos.get_security_rule'](rulename, vsys)['result'] if rule and 'entry' in rule: rule = rule['entry'] else: rule = {} # Build the rule element element = "" if sourcezone: element += "<from>{0}</from>".format(_build_members(sourcezone, True)) else: ret.update({'comment': "The sourcezone field must be provided."}) return ret if destinationzone: element += "<to>{0}</to>".format(_build_members(destinationzone, True)) else: ret.update({'comment': "The destinationzone field must be provided."}) return ret if source: element += "<source>{0}</source>".format(_build_members(source, True)) else: ret.update({'comment': "The source field must be provided."}) return if destination: element += "<destination>{0}</destination>".format(_build_members(destination, True)) else: ret.update({'comment': "The destination field must be provided."}) return ret if application: element += "<application>{0}</application>".format(_build_members(application, True)) else: ret.update({'comment': "The application field must be provided."}) return ret if service: element += "<service>{0}</service>".format(_build_members(service, True)) else: ret.update({'comment': "The service field must be provided."}) return ret if action: element += "<action>{0}</action>".format(action) else: ret.update({'comment': "The action field must be provided."}) return ret if disabled is not None: if disabled: element += "<disabled>yes</disabled>" else: element += "<disabled>no</disabled>" if description: element += "<description>{0}</description>".format(description) if logsetting: element += "<log-setting>{0}</log-setting>".format(logsetting) if logstart is not None: if logstart: element += "<log-start>yes</log-start>" else: element += "<log-start>no</log-start>" if logend is not None: if logend: element += "<log-end>yes</log-end>" else: element += "<log-end>no</log-end>" if negatesource is not None: if negatesource: element += "<negate-source>yes</negate-source>" else: element += "<negate-source>no</negate-source>" if negatedestination is not None: if negatedestination: element += "<negate-destination>yes</negate-destination>" else: element += "<negate-destination>no</negate-destination>" # Build the profile settings profile_string = None if profilegroup: profile_string = "<group><member>{0}</member></group>".format(profilegroup) else: member_string = "" if datafilter: member_string += "<data-filtering><member>{0}</member></data-filtering>".format(datafilter) if fileblock: member_string += "<file-blocking><member>{0}</member></file-blocking>".format(fileblock) if spyware: member_string += "<spyware><member>{0}</member></spyware>".format(spyware) if urlfilter: member_string += "<url-filtering><member>{0}</member></url-filtering>".format(urlfilter) if virus: member_string += "<virus><member>{0}</member></virus>".format(virus) if vulnerability: member_string += "<vulnerability><member>{0}</member></vulnerability>".format(vulnerability) if wildfire: member_string += "<wildfire-analysis><member>{0}</member></wildfire-analysis>".format(wildfire) if member_string != "": profile_string = "<profiles>{0}</profiles>".format(member_string) if profile_string: element += "<profile-setting>{0}</profile-setting>".format(profile_string) full_element = "<entry name='{0}'>{1}</entry>".format(rulename, element) new_rule = xml.to_dict(ET.fromstring(full_element), True) config_change = False if rule == new_rule: ret.update({ 'comment': 'Security rule already exists. No changes required.' }) else: config_change = True xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret ret.update({ 'changes': {'before': rule, 'after': new_rule}, 'comment': 'Security rule verified successfully.' }) if move: movepath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/rulebase/" \ "security/rules/entry[@name=\'{1}\']".format(vsys, rulename) move_result = False move_msg = '' if move == "before" and movetarget: move_result, move_msg = _move_before(movepath, movetarget) elif move == "after": move_result, move_msg = _move_after(movepath, movetarget) elif move == "top": move_result, move_msg = _move_top(movepath) elif move == "bottom": move_result, move_msg = _move_bottom(movepath) if config_change: ret.update({ 'changes': {'before': rule, 'after': new_rule, 'move': move_msg} }) else: ret.update({ 'changes': {'move': move_msg} }) if not move_result: ret.update({ 'comment': move_msg }) return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) else: ret.update({ 'result': True }) return ret def service_exists(name, servicename=None, vsys=1, protocol=None, port=None, description=None, commit=False): ''' Ensures that a service object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. name: The name of the module function to execute. servicename(str): The name of the security object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. protocol(str): The protocol that is used by the service object. The only valid options are tcp and udp. port(str): The port number that is used by the service object. This can be specified as a single integer or a valid range of ports. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service/tcp-80: panos.service_exists: - servicename: tcp-80 - vsys: 1 - protocol: tcp - port: 80 - description: Hypertext Transfer Protocol - commit: False panos/service/udp-500-550: panos.service_exists: - servicename: udp-500-550 - vsys: 3 - protocol: udp - port: 500-550 - commit: False ''' ret = _default_ret(name) if not servicename: ret.update({'comment': "The service name field must be provided."}) return ret # Check if service object currently exists service = __salt__['panos.get_service'](servicename, vsys)['result'] if service and 'entry' in service: service = service['entry'] else: service = {} # Verify the arguments if not protocol and protocol not in ['tcp', 'udp']: ret.update({'comment': "The protocol must be provided and must be tcp or udp."}) return ret if not port: ret.update({'comment': "The port field must be provided."}) return ret element = "<protocol><{0}><port>{1}</port></{0}></protocol>".format(protocol, port) if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(servicename, element) new_service = xml.to_dict(ET.fromstring(full_element), True) if service == new_service: ret.update({ 'comment': 'Service object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service/" \ "entry[@name=\'{1}\']".format(vsys, servicename) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': service, 'after': new_service}, 'commit': __salt__['panos.commit'](), 'comment': 'Service object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': service, 'after': new_service}, 'comment': 'Service object successfully configured.', 'result': True }) return ret def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will enforce group membership. If a group exists and contains members this state does not include, those members will be removed and replaced with the specified members in the state. name: The name of the module function to execute. groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters, which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on Panorama, unique within its device group and any ancestor or descendant device groups. vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1. members(str, list): The members of the service group. These must be valid service objects or service groups on the system that already exist prior to the execution of this state. description(str): A description for the policy (up to 255 characters). commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/service-group/my-group: panos.service_group_exists: - groupname: my-group - vsys: 1 - members: - tcp-80 - custom-port-group - description: A group that needs to exist - commit: False ''' ret = _default_ret(name) if not groupname: ret.update({'comment': "The group name field must be provided."}) return ret # Check if service group object currently exists group = __salt__['panos.get_service_group'](groupname, vsys)['result'] if group and 'entry' in group: group = group['entry'] else: group = {} # Verify the arguments if members: element = "<members>{0}</members>".format(_build_members(members, True)) else: ret.update({'comment': "The group members must be provided."}) return ret if description: element += "<description>{0}</description>".format(description) full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element) new_group = xml.to_dict(ET.fromstring(full_element), True) if group == new_group: ret.update({ 'comment': 'Service group object already exists. No changes required.', 'result': True }) return ret else: xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \ "entry[@name=\'{1}\']".format(vsys, groupname) result, msg = _edit_config(xpath, full_element) if not result: ret.update({ 'comment': msg }) return ret if commit is True: ret.update({ 'changes': {'before': group, 'after': new_group}, 'commit': __salt__['panos.commit'](), 'comment': 'Service group object successfully configured.', 'result': True }) else: ret.update({ 'changes': {'before': group, 'after': new_group}, 'comment': 'Service group object successfully configured.', 'result': True }) return ret def set_config(name, xpath=None, value=None, commit=False): ''' Sets a Palo Alto XPATH to a specific value. This will always overwrite the existing value, even if it is not changed. You can add or create a new object at a specified location in the configuration hierarchy. Use the xpath parameter to specify the location of the object in the configuration name: The name of the module function to execute. xpath(str): The XPATH of the configuration API tree to control. value(str): The XML value to set. This must be a child to the XPATH. commit(bool): If true the firewall will commit the changes, if false do not commit changes. SLS Example: .. code-block:: yaml panos/hostname: panos.set_config: - xpath: /config/devices/entry[@name='localhost.localdomain']/deviceconfig/system - value: <hostname>foobar</hostname> - commit: True ''' ret = _default_ret(name) result, msg = _set_config(xpath, value) ret.update({ 'comment': msg, 'result': result }) if not result: return ret if commit is True: ret.update({ 'commit': __salt__['panos.commit'](), 'result': True }) return ret