text
stringlengths
81
112k
Lookup style by either element name or the list of classes def _lookup_style(element, names): ''' Lookup style by either element name or the list of classes ''' return _STYLES.get('_'+element, '') + \ ''.join([_STYLES.get(name, '') for name in names])
Generate a single table of data def _generate_html_table(data, out, level=0, extra_style=''): ''' Generate a single table of data ''' print('<table style="{0}">'.format( _lookup_style('table', ['table' + six.text_type(level)])), file=out) firstone = True row_style = 'row' + six.text_t...
Generate report data as HTML def _generate_html(data, out): ''' Generate report data as HTML ''' print('<html>', file=out) print('<body>', file=out) _generate_html_table(data, out, 0) print('</body>', file=out) print('</html>', file=out)
Convert a dictionary to a list of dictionaries to facilitate ordering def _dict_to_name_value(data): ''' Convert a dictionary to a list of dictionaries to facilitate ordering ''' if isinstance(data, dict): sorted_data = sorted(data.items(), key=lambda s: s[0]) result = [] for na...
Generate states report def _generate_states_report(sorted_data): ''' Generate states report ''' states = [] for state, data in sorted_data: module, stateid, name, function = state.split('_|-') module_function = '.'.join((module, function)) result = data.get('result', '') ...
Generate report dictionary def _generate_report(ret, setup): ''' Generate report dictionary ''' retdata = ret.get('return', {}) sorted_data = sorted( retdata.items(), key=lambda s: s[1].get('__run_num__', 0) ) total = 0 failed = 0 changed = 0 duration = 0.0 ...
Produce output from the report dictionary generated by _generate_report def _produce_output(report, failed, setup): ''' Produce output from the report dictionary generated by _generate_report ''' report_format = setup.get('report_format', 'yaml') log.debug('highstate output format: %s', report_for...
Check highstate return information and possibly fire off an email or save a file. def returner(ret): ''' Check highstate return information and possibly fire off an email or save a file. ''' setup = _get_options(ret) log.debug('highstate setup %s', setup) report, failed = _generate_re...
Return the formatted outputter string for the Python object. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs Arguments ...
Return the outputter formatted string, removing the ANSI escape sequences. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs ...
Return the formatted string as HTML. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs Arguments to sent to the outputter...
Install buildout in a specific directory It is a thin wrapper to modules.buildout.buildout name directory to execute in quiet do not output console & logs config buildout config to use (default: buildout.cfg) parts specific buildout parts to run user ...
Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2>...
Set an object permission for the given user sid def set_user_perm(obj, perm, sid): ''' Set an object permission for the given user sid ''' info = ( win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION )...
Grant the token's user access to the current process's window station and desktop. def grant_winsta_and_desktop(th): ''' Grant the token's user access to the current process's window station and desktop. ''' current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] # A...
Enumerate tokens from any existing processes that can be accessed. Optionally filter by sid. def enumerate_tokens(sid=None, session_id=None, privs=None): ''' Enumerate tokens from any existing processes that can be accessed. Optionally filter by sid. ''' for p in psutil.process_iter(): ...
Find an existing process token for the given sid and impersonate the token. def impersonate_sid(sid, session_id=None, privs=None): ''' Find an existing process token for the given sid and impersonate the token. ''' for tok in enumerate_tokens(sid, session_id, privs): tok = dup_token(tok) ...
duplicate the access token def dup_token(th): ''' duplicate the access token ''' # TODO: is `duplicate_token` the same? sec_attr = win32security.SECURITY_ATTRIBUTES() sec_attr.bInheritHandle = True return win32security.DuplicateTokenEx( th, win32security.SecurityImpersonation,...
Set all token priviledges to enabled def elevate_token(th): ''' Set all token priviledges to enabled ''' # Get list of privileges this token contains privileges = win32security.GetTokenInformation( th, win32security.TokenPrivileges) # Create a set of all privileges to be enabled en...
Create an inheritable handle def make_inheritable(token): '''Create an inheritable handle''' return win32api.DuplicateHandle( win32api.GetCurrentProcess(), token, win32api.GetCurrentProcess(), 0, 1, win32con.DUPLICATE_SAME_ACCESS )
Ensure the CloudFront distribution is present. name (string) Name of the CloudFront distribution config (dict) Configuration for the distribution tags (dict) Tags to associate with the distribution region (string) Region to connect to key (string) Secret ...
Stupidly simple function to fix any Items/Quantity disparities inside a DistributionConfig block before use. Since AWS only accepts JSON-encodable data types, this implementation is "good enough" for our purposes. def _fix_quantities(tree): ''' Stupidly simple function to fix any Items/Quantity dispari...
Ensure the given CloudFront distribution exists in the described state. The implementation of this function, and all those following, is orthagonal to that of :py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`. Resources created with :py:mod:`boto_cloudfront.present <salt.states.bo...
Ensure the given policy exists on an S3 bucket, granting access for the given origin access identity to do the things specified in the policy. name The name of the state definition Bucket The S3 bucket which CloudFront needs access to. Note that this policy is exclusive - it will b...
Ensure a Route53 Alias exists and is pointing at the given CloudFront distribution. An ``A`` record is always created, and if IPV6 is enabled on the given distribution, an ``AAAA`` record will be created as well. Also be aware that Alias records for CloudFront distributions are only permitted in non-pri...
Ensure a distribution with the given Name tag does not exist. Note that CloudFront does not allow directly deleting an enabled Distribution. If such is requested, Salt will attempt to first update the distribution's status to Disabled, and once that returns success, to then delete the resource. THIS CA...
Ensure a given CloudFront Origin Access Identity exists. .. note:: Due to the unavailibity of ANY other way to store stateful idempotency information about Origin Access Identities (including resource tags), the Comment attribute (as the only user-settable attribute without weird se...
Ensure a given CloudFront Origin Access Identity is absent. name The name of the state definition. Name (string) Name of the resource (for purposes of Salt's idempotency). If not provided, the value of ``name`` will be used. Id (string) The Resource ID of a CloudFront orig...
Install the specified snap package from the specified channel. Returns a dictionary of "result" and "output". pkg The snap package name channel Optional. The snap channel to install from, eg "beta" refresh : False If True, use "snap refresh" instead of "snap install". ...
Remove the specified snap package. Returns a dictionary of "result" and "output". pkg The package name def remove(pkg): ''' Remove the specified snap package. Returns a dictionary of "result" and "output". pkg The package name ''' ret = {'result': None, 'output': ""} try: ...
Query which version(s) of the specified snap package are installed. Returns a list of 0 or more dictionaries. pkg The package name def versions_installed(pkg): ''' Query which version(s) of the specified snap package are installed. Returns a list of 0 or more dictionaries. pkg ...
Create a virtualenv path The path to the virtualenv to be created venv_bin The name (and optionally path) of the virtualenv command. This can also be set globally in the pillar data as ``venv_bin``. Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed. ...
Return the path to the site-packages directory of a virtualenv venv Path to the virtualenv. CLI Example: .. code-block:: bash salt '*' virtualenv.get_site_packages /path/to/my/venv def get_site_packages(venv): ''' Return the path to the site-packages directory of a virtualenv ...
Return the path to a distribution installed inside a virtualenv .. versionadded:: 2016.3.0 venv Path to the virtualenv. distribution Name of the distribution. Note, all non-alphanumeric characters will be converted to dashes. CLI Example: .. code-block:: bash sal...
Return the path to a package resource installed inside a virtualenv .. versionadded:: 2015.5.0 venv Path to the virtualenv package Name of the package in which the resource resides .. versionadded:: 2016.3.0 resource Name of the resource of which the path is to be re...
Return a list of the VMs id (str) image (str) size (str) state (str) private_ips (list) public_ips (list) def list_nodes(call=None): ''' Return a list of the VMs id (str) image (str) size (str) state (str) private_ips (list) public_ips (list) ''' if ca...
Return a list of the VMs that are on the provider, with select fields 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_select function must be called ' ...
Provision a single machine def create(vm_): ''' Provision a single machine ''' clone_strategy = vm_.get('clone_strategy') or 'full' if clone_strategy not in ('quick', 'full'): raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy)) ...
Clean up clone domain leftovers as much as possible. Extra robust clean up in order to deal with some small changes in libvirt behavior over time. Passed in volumes and domains are deleted, any errors are ignored. Used when cloning/provisioning a domain fails. :param cleanup: list containing dictonari...
This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is fired. The tag for that event is `salt/...
Print out via pretty print def output(data, **kwargs): # pylint: disable=unused-argument ''' Print out via pretty print ''' if isinstance(data, Exception): data = six.text_type(data) if 'output_indent' in __opts__ and __opts__['output_indent'] >= 0: return pprint.pformat(data, inde...
Return the VM's size object def get_size(vm_): ''' Return the VM's size object ''' vm_size = config.get_cloud_config_value( 'fixed_instance_size', vm_, __opts__, default=None, search_global=False ) sizes = avail_sizes() if not vm_size: size = next((item for item in ...
Return the image object to use def get_image(vm_): ''' Return the image object to use ''' vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode( 'ascii', 'salt-cloud-force-ascii' ) images = avail_images() for key, value in six.iteritems(images): if vm_imag...
List available locations/datacenters for 1&1 def avail_locations(conn=None, call=None): ''' List available locations/datacenters for 1&1 ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the...
Create a block storage def create_block_storage(kwargs=None, call=None): ''' Create a block storage ''' if call == 'action': raise SaltCloudSystemExit( 'The create_block_storage function must be called with ' '-f or --function' ) conn = get_conn() # Ass...
Construct a block storage instance from passed arguments def _get_block_storage(kwargs): ''' Construct a block storage instance from passed arguments ''' if kwargs is None: kwargs = {} block_storage_name = kwargs.get('name', None) block_storage_size = kwargs.get('size', None) block...
Construct an SshKey instance from passed arguments def _get_ssh_key(kwargs): ''' Construct an SshKey instance from passed arguments ''' ssh_key_name = kwargs.get('name', None) ssh_key_description = kwargs.get('description', None) public_key = kwargs.get('public_key', None) return SshKey( ...
Create an ssh key def create_ssh_key(kwargs=None, call=None): ''' Create an ssh key ''' if call == 'action': raise SaltCloudSystemExit( 'The create_ssh_key function must be called with ' '-f or --function' ) conn = get_conn() # Assemble the composite Ss...
Construct FirewallPolicy and FirewallPolicy instances from passed arguments def _get_firewall_policy(kwargs): ''' Construct FirewallPolicy and FirewallPolicy instances from passed arguments ''' fp_name = kwargs.get('name', None) fp_description = kwargs.get('description', None) firewallPolicy = ...
Create a firewall policy def create_firewall_policy(kwargs=None, call=None): ''' Create a firewall policy ''' if call == 'action': raise SaltCloudSystemExit( 'The create_firewall_policy function must be called with ' '-f or --function' ) conn = get_conn() ...
Return a list of the server appliances that are on the provider def avail_images(conn=None, call=None): ''' Return a list of the server appliances that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' ...
Return a list of the baremetal server appliances that are on the provider def avail_baremetal_images(conn=None, call=None): ''' Return a list of the baremetal server appliances that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_baremetal_images f...
Return a dict of all available VM sizes on the cloud provider with relevant data. def avail_sizes(call=None): ''' Return a dict of all available VM sizes on the cloud provider with relevant data. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function m...
Return a dict of all available baremetal models with relevant data. def baremetal_models(call=None): ''' Return a dict of all available baremetal models with relevant data. ''' if call == 'action': raise SaltCloudSystemExit( 'The baremetal_models function must be called with ' ...
Return a list of VMs that are on the provider def list_nodes(conn=None, call=None): ''' Return a list of VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) if not conn: ...
Return a list of the VMs that are on the provider, with all fields def list_nodes_full(conn=None, call=None): ''' Return a list of the VMs that are on the provider, with all fields ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with ...
Construct server instance from cloud profile config def _get_server(vm_): ''' Construct server instance from cloud profile config ''' description = config.get_cloud_config_value( 'description', vm_, __opts__, default=None, search_global=False ) ssh_key = load_public_key(vm_) ...
Construct VM hdds from cloud profile config def _get_hdds(vm_): ''' Construct VM hdds from cloud profile config ''' _hdds = config.get_cloud_config_value( 'hdds', vm_, __opts__, default=None, search_global=False ) hdds = [] for hdd in _hdds: hdds.append( ...
Create a single VM from a data dict def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if (vm_['profile'] and config.is_profile_configured(__opts__, (_...
destroy a server by name :param name: name given to the server :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: .. code-block:: bash salt-cloud -d vm_name def destroy(nam...
reboot a server by name :param name: name given to the machine :param call: call value in this case is 'action' :return: true if successful CLI Example: .. code-block:: bash salt-cloud -a reboot vm_name def reboot(name, call=None): ''' reboot a server by name :param name: nam...
Return a node for the named VM def get_node(conn, name): ''' Return a node for the named VM ''' for node in conn.list_servers(per_page=1000): if node['name'] == name: return node
Load the public key file if exists. def load_public_key(vm_): ''' Load the public key file if exists. ''' public_key_filename = config.get_cloud_config_value( 'ssh_public_key', vm_, __opts__, search_global=False, default=None ) if public_key_filename is not None: public_key_file...
Poll request status until resource is provisioned. def _wait_for_completion(conn, wait_timeout, server_id): ''' Poll request status until resource is provisioned. ''' wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): time.sleep(5) server = conn.get_server(...
format the results of listing functions def _load_result(response, ret): ''' format the results of listing functions ''' #were we able to connect? if response['code'] is None: ret['comment'] = response['content'] #forbidden? elif response['code'] == 401: ret['comment'] = '4...
look for a certain key within a dictionary and nullify ti's contents, check within nested dictionaries and lists as well. Certain attributes such as "generation" will change even when there were no changes made to the entity. def _strip_key(dictionary, keyword): ''' look for a certain key within a dic...
take an existing entity and a modified entity and check for changes. def _check_for_changes(entity_type, ret, existing, modified): ''' take an existing entity and a modified entity and check for changes. ''' ret['result'] = True #were there any changes? generation always changes, remove it. ...
Create a new node if it does not already exist. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to create address The address of the node def create_node(hostname...
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise, only the properties which are different than the existing will be updated. hostname The host/address of the bigip device username The iControl REST username password The iControl R...
Modify an existing node. Only a node which already exists will be modified and only the parameters specified will be enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the n...
Create a new node if it does not already exist. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to create members List of members to be added to the pool allow...
Create a new pool if it does not already exist. Pool members are managed separately. Only the parameters specified are enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the...
Delete an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted def delete_pool(hostname, username, password, name): ''' Delete an exis...
Manage the members of an existing pool. This function replaces all current pool members. Only the parameters specified are enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name o...
A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The member to ad...
A function to connect to a bigip device and modify a member of an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The member modify...
Delete an existing pool member. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to be modified member The name of the member to delete from the pool def delete_po...
A function to list a specific virtual. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to list def list_virtual(hostname, username, password, name): ''' A function...
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the parameters specified will be enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of...
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destinatio...
A function to connect to a bigip device and create a monitor. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password monitor_type The type of monitor to create name The name of the monitor to crea...
r''' A function to connect to a bigip device and create a profile. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password profile_type The type of profile to create name The name of the profil...
Return a list of the images that are on the provider. def avail_images(call=None): ''' Return a list of the images that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --...
Return a list of the BareMetal servers that are on the provider. def list_nodes(call=None): ''' Return a list of the BareMetal servers that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ...
Return a list of the BareMetal servers that are on the provider. def list_nodes_full(call=None): ''' Return a list of the BareMetal servers that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit( 'list_nodes_full must be called with -f or --function' ) ...
Return the image object to use. def get_image(server_): ''' Return the image object to use. ''' images = avail_images() server_image = six.text_type(config.get_cloud_config_value( 'image', server_, __opts__, search_global=False )) for image in images: if server_image in (images[...
Create a node. def create_node(args): ''' Create a node. ''' node = query(method='servers', args=args, http_method='POST') action = query( method='servers', server_id=node['server']['id'], command='action', args={'action': 'poweron'}, http_method='POST' ) ...
Create a single BareMetal server from a data dict. def create(server_): ''' Create a single BareMetal server from a data dict. ''' try: # Check for required profile parameters before sending any API calls. if server_['profile'] and config.is_profile_configured(__opts__, ...
Make a call to the Scaleway API. def query(method='servers', server_id=None, command=None, args=None, http_method='GET', root='api_root'): ''' Make a call to the Scaleway API. ''' if root == 'api_root': default_url = 'https://cp-par1.scaleway.com' else: default_url = 'https:/...
Return the script deployment object. def script(server_): ''' Return the script deployment object. ''' return salt.utils.cloud.os_script( config.get_cloud_config_value('script', server_, __opts__), server_, __opts__, salt.utils.cloud.salt_config_to_yaml( salt.uti...
Verifies that the specified SSH key is present for the specified user name The SSH key to manage user The user who owns the SSH authorized keys file to modify enc Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa or ssh-dss comment The com...
Verifies that the specified SSH key is absent name The SSH key to manage user The user who owns the SSH authorized keys file to modify enc Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa or ssh-dss comment The comment to be placed with t...
.. versionadded:: Neon Ensures that only the specified ssh_keys are present for the specified user ssh_keys The SSH key to manage user The user who owns the SSH authorized keys file to modify enc Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa o...
Multi action helper for start, stop, get, ... def _action(action='get', search=None, one=True, force=False): ''' Multi action helper for start, stop, get, ... ''' vms = {} matched_vms = [] client = salt.client.get_local_client(__opts__['conf_file']) ## lookup vms try: vmadm_arg...
List all compute nodes verbose : boolean print additional information about the node e.g. platform version, hvm capable, ... CLI Example: .. code-block:: bash salt-run vmadm.nodes salt-run vmadm.nodes verbose=True def nodes(verbose=False): ''' List all compute no...
List all vms search : string filter vms, see the execution module verbose : boolean print additional information about the vm CLI Example: .. code-block:: bash salt-run vmadm.list salt-run vmadm.list search='type=KVM' salt-run vmadm.list verbose=True def list...
Reboot one or more vms search : string filter vms, see the execution module. one : boolean reboot only one vm force : boolean force reboot, faster but no graceful shutdown .. note:: If the search parameter does not contain an equal (=) symbol it will be assumed ...
Convert an XML tree into a dict def _xml_to_dict(xmltree): ''' Convert an XML tree into a dict ''' if sys.version_info < (2, 7): children_len = len(xmltree.getchildren()) else: children_len = len(xmltree) if children_len < 1: name = xmltree.tag if '}' in name: ...
Return an optimized list of providers. We want to reduce the duplication of querying the same region. If a provider is using the same credentials for the same region the same data will be returned for each provider, thus causing un-wanted duplicate data and API calls to EC2. def optimize_provider...
Helper function that waits for a spot instance request to become active for a specific maximum amount of time. :param update_callback: callback function which queries the cloud provider for spot instance request. It must return None if the required data, ...