INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Pull salt file references out of the states
def salt_refs(data): ''' Pull salt file references out of the states ''' proto = 'salt://' ret = [] if isinstance(data, six.string_types): if data.startswith(proto): return [data] if isinstance(data, list): for comp in data: if isinstance(comp, six.str...
Generate the module arguments for the shim data
def mod_data(fsclient): ''' Generate the module arguments for the shim data ''' # TODO, change out for a fileserver backend sync_refs = [ 'modules', 'states', 'grains', 'renderers', 'returners', ] ret = {} envs = fsclien...
Returns the version of the installed ssh command
def ssh_version(): ''' Returns the version of the installed ssh command ''' # This function needs more granular checks and to be validated against # older versions of ssh ret = subprocess.Popen( ['ssh', '-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).co...
Take a list of args, and convert any dicts inside the list to keyword args in the form of `key=value`, ready to be passed to salt-ssh
def _convert_args(args): ''' Take a list of args, and convert any dicts inside the list to keyword args in the form of `key=value`, ready to be passed to salt-ssh ''' converted = [] for arg in args: if isinstance(arg, dict): for key in list(arg.keys()): if key...
Read roster filename as a key to the data. :return:
def _get_roster(self): ''' Read roster filename as a key to the data. :return: ''' roster_file = salt.roster.get_roster_file(self.opts) if roster_file not in self.__parsed_rosters: roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}), ...
Figures out if the target is a reachable host without wildcards, expands if any. :return:
def _expand_target(self): ''' Figures out if the target is a reachable host without wildcards, expands if any. :return: ''' # TODO: Support -L target = self.opts['tgt'] if isinstance(target, list): return hostname = self.opts['tgt'].split('@')...
Update default flat roster with the passed in information. :return:
def _update_roster(self): ''' Update default flat roster with the passed in information. :return: ''' roster_file = self._get_roster() if os.access(roster_file, os.W_OK): if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]: with salt.utils.files....
Uptade targets in case hostname was directly passed without the roster. :return:
def _update_targets(self): ''' Uptade targets in case hostname was directly passed without the roster. :return: ''' hostname = self.opts.get('tgt', '') if '@' in hostname: user, hostname = hostname.split('@', 1) else: user = self.opts.get(...
Return the key string for the SSH public key
def get_pubkey(self): ''' Return the key string for the SSH public key ''' if '__master_opts__' in self.opts and \ self.opts['__master_opts__'].get('ssh_use_home_key') and \ os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')): priv = os.path.ex...
Deploy the SSH key if the minions don't auth
def key_deploy(self, host, ret): ''' Deploy the SSH key if the minions don't auth ''' if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'): target = self.targets[host] if target.get('passwd', False) or self.opts['ssh_passwd']: self...
The ssh-copy-id routine
def _key_deploy_run(self, host, target, re_run=True): ''' The ssh-copy-id routine ''' argv = [ 'ssh.set_auth_key', target.get('user', 'root'), self.get_pubkey(), ] single = Single( self.opts, argv, ...
Run the routine in a "Thread", put a dict on the queue
def handle_routine(self, que, opts, host, target, mine=False): ''' Run the routine in a "Thread", put a dict on the queue ''' opts = copy.deepcopy(opts) single = Single( opts, opts['argv'], host, mods=self.mods, ...
Spin up the needed threads or processes and execute the subsequent routines
def handle_ssh(self, mine=False): ''' Spin up the needed threads or processes and execute the subsequent routines ''' que = multiprocessing.Queue() running = {} target_iter = self.targets.__iter__() returned = set() rets = set() init = Fals...
Execute and yield returns as they come in, do not print to the display mine The Single objects will use mine_functions defined in the roster, pillar, or master config (they will be checked in that order) and will modify the argv with the arguments from mine_functions
def run_iter(self, mine=False, jid=None): ''' Execute and yield returns as they come in, do not print to the display mine The Single objects will use mine_functions defined in the roster, pillar, or master config (they will be checked in that order) and will ...
Cache the job information
def cache_job(self, jid, id_, ret, fun): ''' Cache the job information ''' self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid, 'id': id_, ...
Execute the overall routine, print results via outputters
def run(self, jid=None): ''' Execute the overall routine, print results via outputters ''' if self.opts.get('list_hosts'): self._get_roster() ret = {} for roster_file in self.__parsed_rosters: if roster_file.startswith('#'): ...
Return the function name and the arg list
def __arg_comps(self): ''' Return the function name and the arg list ''' fun = self.argv[0] if self.argv else '' parsed = salt.utils.args.parse_input( self.argv[1:], condition=False, no_parse=self.opts.get('no_parse', [])) args = parsed...
Properly escape argument to protect special characters from shell interpretation. This avoids having to do tricky argument quoting. Effectively just escape all characters in the argument that are not alphanumeric!
def _escape_arg(self, arg): ''' Properly escape argument to protect special characters from shell interpretation. This avoids having to do tricky argument quoting. Effectively just escape all characters in the argument that are not alphanumeric! ''' if self.winr...
Deploy salt-thin
def deploy(self): ''' Deploy salt-thin ''' self.shell.send( self.thin, os.path.join(self.thin_dir, 'salt-thin.tgz'), ) self.deploy_ext() return True
Deploy the ext_mods tarball
def deploy_ext(self): ''' Deploy the ext_mods tarball ''' if self.mods.get('file'): self.shell.send( self.mods['file'], os.path.join(self.thin_dir, 'salt-ext_mods.tgz'), ) return True
Execute the routine, the routine can be either: 1. Execute a raw shell command 2. Execute a wrapper func 3. Execute a remote Salt command If a (re)deploy is needed, then retry the operation after a deploy attempt Returns tuple of (stdout, stderr, retcode)
def run(self, deploy_attempted=False): ''' Execute the routine, the routine can be either: 1. Execute a raw shell command 2. Execute a wrapper func 3. Execute a remote Salt command If a (re)deploy is needed, then retry the operation after a deploy attempt ...
Execute a wrapper function Returns tuple of (json_data, '')
def run_wfunc(self): ''' Execute a wrapper function Returns tuple of (json_data, '') ''' # Ensure that opts/grains are up to date # Execute routine data_cache = False data = None cdir = os.path.join(self.opts['cachedir'], 'minions', self.id) ...
Prepare the command string
def _cmd_str(self): ''' Prepare the command string ''' sudo = 'sudo' if self.target['sudo'] else '' sudo_user = self.target['sudo_user'] if '_caller_cachedir' in self.opts: cachedir = self.opts['_caller_cachedir'] else: cachedir = self.opts...
Run a shim command. If tty is enabled, we must scp the shim to the target system and execute it there
def shim_cmd(self, cmd_str, extension='py'): ''' Run a shim command. If tty is enabled, we must scp the shim to the target system and execute it there ''' if not self.tty and not self.winrm: return self.shell.exec_cmd(cmd_str) # Write the shim to a t...
Prepare the pre-check command to send to the subsystem 1. execute SHIM + command 2. check if SHIM returns a master request or if it completed 3. handle any master request 4. re-execute SHIM + command 5. split SHIM results from command results 6. return command results
def cmd_block(self, is_retry=False): ''' Prepare the pre-check command to send to the subsystem 1. execute SHIM + command 2. check if SHIM returns a master request or if it completed 3. handle any master request 4. re-execute SHIM + command 5. split SHIM results ...
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_type(level) cell_style = 'cell...
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)
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', '') single = [ ...
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 # gather stats for _,...
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_format) if report_format == 'json': report_text = salt.utils.js...
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_report(ret, setup) if report: _produce_output(report, failed, setup)
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 ...
def out_format(data, out='nested', opts=None, **kwargs): ''' 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 configu...
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 ...
def string_format(data, out='nested', opts=None, **kwargs): ''' 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 Dict...
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...
def html_format(data, out='nested', opts=None, **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...
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 ...
def installed(name, config='buildout.cfg', quiet=False, parts=None, user=None, env=(), buildout_ver=None, test_release=False, distribute=None, new_st=None, offline=False, ...
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>...
def version(*names, **kwargs): ''' 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> ...
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 ) sd = win32security.GetUserObjectSecurity(obj...
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] # Add permissions for the sid to the current windows station and thread id. # This prev...
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(): if p.pid == 0: continue try: ph = win32api.OpenProcess(win32con.PR...
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) elevate_token(tok) if win32security.ImpersonateLoggedOnUser(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, win32con.MAXIMUM_ALL...
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 enable_privs = set() for luid, flags...
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 )
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 disparities inside a DistributionConfig block before use. Since AWS only accepts JSON-encodable data types, this implementation is "good enough" for our purposes. ''' if isinstance(tree, dict): tree = {k: _...
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...
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' 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...
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...
def oai_bucket_policy_present(name, Bucket, OAI, Policy, region=None, key=None, keyid=None, profile=None): ''' 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 na...
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...
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' 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 w...
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...
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' 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 dist...
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...
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' 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 (incl...
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...
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' 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 ...
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". ...
def install(pkg, channel=None, refresh=False): ''' 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 T...
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: ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, 'remove', pkg]) ret['result'] = True e...
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 The package name ''' try: # Try to run it, merging stderr into output output = subprocess.check_output([SNAP_BINARY_NAME, '...
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. ...
def create(path, venv_bin=None, system_site_packages=False, distribute=False, clear=False, python=None, extra_search_dir=None, never_download=None, prompt=None, pip=False, symlinks=None, upgrade=None...
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 venv Path to the virtualenv. CLI Example: .. code-block:: bash salt '*' virtualenv.get_site_packages /path/to/my/venv ''' bin_path = _verify_virtualenv(venv) ret = __salt_...
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...
def get_distribution_path(venv, distribution): ''' 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 dashe...
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...
def get_resource_path(venv, package=None, resource=None): ''' 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 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 call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called ' 'with -f or --f...
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 ' 'with -f or --function.' ) selection = __opts__.ge...
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)) ip_source = vm_.get('ip_sour...
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...
def do_cleanup(cleanup): ''' 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. :par...
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/...
def destroy(name, call=None): """ 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 f...
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, indent=__opts__['output_indent']...
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 sizes if item['name'] == 'S')...
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_image and vm_image in (images[key]['...
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 --list-locations option' ) datac...
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() # Assemble the composite bloc...
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_storage_description = kwargs.get('description', None) ...
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( name=ssh_key_name, description=ssh_ke...
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 SshKey object. 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 = FirewallPolicy( name=fp_name, description=fp_description ...
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() # Assemble the composit...
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 ' '-f or --function, or with the --list-images option' ) ...
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 function must be called with ' '-f or --function' ) ...
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 must be called with ' '-f or --function, or with the --list-sizes option' ...
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 ' '-f or --function' ) conn = get_conn() bmode...
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: conn = get_conn() ret = {} nodes = ...
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 -f or ' '--function.' ) if not conn: ...
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_) server_type = config.get_cloud_config_value( ...
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( Hdd( size=hdd['size'], ...
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__, (__active_provider_name__ or ...
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(name, call=None): ''' 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 ...
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: 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 ''' conn = get_conn() node = get_...
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_filename = os.path.expanduser(public_key_...
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(server_id) server_state = server['status']['...
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'] = '401 Forbidden: Authentication required!' ...
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 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. ''' for key, value in six.i...
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. if isinstance(existing, dict) and isinstance(modified, dict): ...
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, username, password, name, address): ''' 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 cr...
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...
def manage_node(hostname, username, password, name, address, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None,...
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...
def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, ...
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...
def create_pool(hostname, username, password, name, members=None, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_t...
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...
def manage_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None,...
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 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 ''' re...
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...
def manage_pool_members(hostname, username, password, name, members): ''' 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 us...
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...
def add_pool_member(hostname, username, password, name, member): ''' 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 na...
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...
def modify_pool_member(hostname, username, password, name, member, connection_limit=None, description=None, dynamic_ratio=None, inherit_profile=None, logging=None, monitor=None, ...
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_pool_member(hostname, username, password, name, member): ''' 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 ...