INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Ensure that the named package is built and exists in the named directory name The name to track the build, the name value is otherwise unused runas The user to run the build process as dest_dir The directory on the minion to place the built package(s) spec The locatio...
def built(name, runas, dest_dir, spec, sources, tgt, template=None, deps=None, env=None, results=None, force=False, saltenv='base', log_dir='/var/log/salt/pkgbuild'): ''' Ensure that the named...
Take the path to a template and return the high data structure derived from the template. Helpers: :param mask_value: Mask value for debugging purposes (prevent sensitive information etc) example: "mask_value="pass*". All "passwd", "password", "pass" will be masked (as text).
def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ''' Take the path to ...
Take template as a string and return the high data structure derived from the template.
def compile_template_str(template, renderers, default, blacklist, whitelist): ''' Take template as a string and return the high data structure derived from the template. ''' fn_ = salt.utils.files.mkstemp() with salt.utils.files.fopen(fn_, 'wb') as ofile: ofile.write(SLS_ENCODER(template...
Check the template shebang line and return the list of renderers specified in the pipe. Example shebang lines:: #!yaml_jinja #!yaml_mako #!mako|yaml #!jinja|yaml #!jinja|mako|yaml #!mako|yaml|stateconf #!jinja|yaml|stateconf #!mako|yaml_odict #!mako|yaml_o...
def template_shebang(template, renderers, default, blacklist, whitelist, input_data): ''' Check the template shebang line and return the list of renderers specified in the pipe. Example shebang lines:: #!yaml_jinja #!yaml_mako #!mako|yaml #!jinja|yaml #!jinja|mako|yaml ...
Check that all renderers specified in the pipe string are available. If so, return the list of render functions in the pipe as (render_func, arg_str) tuples; otherwise return [].
def check_render_pipe_str(pipestr, renderers, blacklist, whitelist): ''' Check that all renderers specified in the pipe string are available. If so, return the list of render functions in the pipe as (render_func, arg_str) tuples; otherwise return []. ''' if pipestr is None: return [] ...
Change the system runlevel on sysV compatible systems CLI Example: state : string Init state .. code-block:: bash salt '*' system.init 3 .. note: state 0 Stop the operating system. state 1 State 1 is referred to as the administrative state. ...
def init(state): ''' Change the system runlevel on sysV compatible systems CLI Example: state : string Init state .. code-block:: bash salt '*' system.init 3 .. note: state 0 Stop the operating system. state 1 State 1 is referred to ...
Reboot the system delay : int Optional wait time in seconds before the system will be rebooted. message : string Optional message to broadcast before rebooting. CLI Example: .. code-block:: bash salt '*' system.reboot salt '*' system.reboot 60 "=== system upgraded ===...
def reboot(delay=0, message=None): ''' Reboot the system delay : int Optional wait time in seconds before the system will be rebooted. message : string Optional message to broadcast before rebooting. CLI Example: .. code-block:: bash salt '*' system.reboot sal...
Return the twilio connection
def _get_twilio(profile): ''' Return the twilio connection ''' creds = __salt__['config.option'](profile) client = TwilioRestClient( creds.get('twilio.account_sid'), creds.get('twilio.auth_token'), ) return client
Send an sms CLI Example: twilio.send_sms twilio-account 'Test sms' '+18019999999' '+18011111111'
def send_sms(profile, body, to, from_): ''' Send an sms CLI Example: twilio.send_sms twilio-account 'Test sms' '+18019999999' '+18011111111' ''' ret = {} ret['message'] = {} ret['message']['sid'] = None client = _get_twilio(profile) try: if TWILIO_5: mes...
Create a list of file ref objects to reconcile
def lowstate_file_refs(chunks, extras=''): ''' Create a list of file ref objects to reconcile ''' refs = {} for chunk in chunks: if not isinstance(chunk, dict): continue saltenv = 'base' crefs = [] for state in chunk: if state == '__env__': ...
Pull salt file references out of the states
def salt_refs(data, ret=None): ''' Pull salt file references out of the states ''' proto = 'salt://' if ret is None: ret = [] if isinstance(data, six.string_types): if data.startswith(proto) and data not in ret: ret.append(data) if isinstance(data, list): ...
Generate the execution package from the saltenv file refs and a low state data structure
def prep_trans_tar(file_client, chunks, file_refs, pillar=None, id_=None, roster_grains=None): ''' Generate the execution package from the saltenv file refs and a low state data structure ''' gendir = tempfile.mkdtemp() trans_tar = salt.utils.files.mkstemp() lowfn = os.path.join(gendir, 'low...
Load up the modules for remote compilation via ssh
def load_modules(self, data=None, proxy=None): ''' Load up the modules for remote compilation via ssh ''' self.functions = self.wrapper self.utils = salt.loader.utils(self.opts) self.serializers = salt.loader.serializers(self.opts) locals_ = salt.loader.minion_mod...
Evaluate master_tops locally
def _master_tops(self): ''' Evaluate master_tops locally ''' if 'id' not in self.opts: log.error('Received call for external nodes without an id') return {} if not salt.utils.verify.valid_id(self.opts, self.opts['id']): return {} # Eval...
Get a resource type api versions
def get_api_versions(call=None, kwargs=None): # pylint: disable=unused-argument ''' Get a resource type api versions ''' if kwargs is None: kwargs = {} if 'resource_provider' not in kwargs: raise SaltCloudSystemExit( 'A resource_provider must be specified' ) ...
Get an AzureARM resource by id
def get_resource_by_id(resource_id, api_version, extract_value=None): ''' Get an AzureARM resource by id ''' ret = {} try: resconn = get_conn(client_type='resource') resource_query = resconn.resources.get_by_id( resource_id=resource_id, api_version=api_versio...
Return the first configured provider instance.
def get_configured_provider(): ''' Return the first configured provider instance. ''' def __is_provider_configured(opts, provider, required_keys=()): ''' Check if the provider is configured. ''' if ':' in provider: alias, driver = provider.split(':') ...
Return a connection object for a client type.
def get_conn(client_type): ''' Return a connection object for a client type. ''' conn_kwargs = {} conn_kwargs['subscription_id'] = salt.utils.stringutils.to_str( config.get_cloud_config_value( 'subscription_id', get_configured_provider(), __opts__, search_global=Fals...
Return the location that is configured for this provider
def get_location(call=None, kwargs=None): # pylint: disable=unused-argument ''' Return the location that is configured for this provider ''' if not kwargs: kwargs = {} vm_dict = get_configured_provider() vm_dict.update(kwargs) return config.get_cloud_config_value( 'location'...
Return a dict of all available regions.
def avail_locations(call=None): ''' Return a dict of all available regions. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) ret = {} ret['loc...
Return a dict of all available images on the provider
def avail_images(call=None): ''' Return a dict of all available images 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' ) compconn = get_co...
Return a list of sizes available from the provider
def avail_sizes(call=None): ''' Return a list of sizes available from the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) compconn = get_conn(cl...
List VMs on this Azure account
def list_nodes(call=None): ''' List VMs on this Azure account ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} nodes = list_nodes_full() for node in nodes: ret[node] = {'name':...
List all VMs on the subscription with full information
def list_nodes_full(call=None): ''' List all VMs on the subscription with full information ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) netapi_versions = get_api_versions(kwargs={ 'reso...
List resource groups associated with the subscription
def list_resource_groups(call=None): ''' List resource groups associated with the subscription ''' if call == 'action': raise SaltCloudSystemExit( 'The list_hosted_services function must be called with ' '-f or --function' ) resconn = get_conn(client_type='re...
Show the details from AzureARM concerning an instance
def show_instance(name, call=None): ''' Show the details from AzureARM concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) try: node = list_nodes_full('function')[name] exc...
Delete a network interface.
def delete_interface(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a network interface. ''' if kwargs is None: kwargs = {} netconn = get_conn(client_type='network') if kwargs.get('resource_group') is None: kwargs['resource_group'] = config.get_cloud_con...
Get the public ip address details by name.
def _get_public_ip(name, resource_group): ''' Get the public ip address details by name. ''' netconn = get_conn(client_type='network') try: pubip_query = netconn.public_ip_addresses.get( resource_group_name=resource_group, public_ip_address_name=name ) ...
Get a network interface.
def _get_network_interface(name, resource_group): ''' Get a network interface. ''' public_ips = [] private_ips = [] netapi_versions = get_api_versions(kwargs={ 'resource_provider': 'Microsoft.Network', 'resource_type': 'publicIPAddresses' } ) netapi_version = neta...
Create a network interface.
def create_network_interface(call=None, kwargs=None): ''' Create a network interface. ''' if call != 'action': raise SaltCloudSystemExit( 'The create_network_interface action must be called with -a or --action.' ) # pylint: disable=invalid-name IPAllocationMethod = g...
Request a VM from Azure.
def request_instance(vm_): ''' Request a VM from Azure. ''' compconn = get_conn(client_type='compute') # pylint: disable=invalid-name CachingTypes = getattr( compute_models, 'CachingTypes' ) # pylint: disable=invalid-name DataDisk = getattr( compute_models, 'DataDisk...
Create a single VM from a data dict.
def create(vm_): ''' Create a single VM from a data dict. ''' try: if vm_['profile'] and config.is_profile_configured( __opts__, __active_provider_name__ or 'azurearm', vm_['profile'], vm_=vm_ ) is False: return False except...
Destroy a VM. CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice
def destroy(name, call=None, kwargs=None): # pylint: disable=unused-argument ''' Destroy a VM. CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice ''' if kwargs is None: kwargs = {} if call == 'function'...
List storage accounts within the subscription.
def list_storage_accounts(call=None): ''' List storage accounts within the subscription. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_storage_accounts function must be called with ' '-f or --function' ) storconn = get_conn(client_type='storag...
Get the cloud environment object.
def _get_cloud_environment(): ''' Get the cloud environment object. ''' cloud_environment = config.get_cloud_config_value( 'cloud_environment', get_configured_provider(), __opts__, search_global=False ) try: clou...
Get the block blob storage service.
def _get_block_blob_service(kwargs=None): ''' Get the block blob storage service. ''' resource_group = kwargs.get('resource_group') or config.get_cloud_config_value( 'resource_group', get_configured_provider(), __opts__, search_global=False ...
List blobs.
def list_blobs(call=None, kwargs=None): # pylint: disable=unused-argument ''' List blobs. ''' if kwargs is None: kwargs = {} if 'container' not in kwargs: raise SaltCloudSystemExit( 'A container must be specified' ) storageservice = _get_block_blob_service(...
Delete a blob from a container.
def delete_blob(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a blob from a container. ''' if kwargs is None: kwargs = {} if 'container' not in kwargs: raise SaltCloudSystemExit( 'A container must be specified' ) if 'blob' not in kwa...
Delete a managed disk from a resource group.
def delete_managed_disk(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a managed disk from a resource group. ''' compconn = get_conn(client_type='compute') try: compconn.disks.delete(kwargs['resource_group'], kwargs['blob']) except Exception as exc: log....
List virtual networks.
def list_virtual_networks(call=None, kwargs=None): ''' List virtual networks. ''' if kwargs is None: kwargs = {} if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function' ) netconn = get_co...
List subnets in a virtual network.
def list_subnets(call=None, kwargs=None): ''' List subnets in a virtual network. ''' if kwargs is None: kwargs = {} if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function' ) netconn = get...
.. versionadded:: 2019.2.0 Create or update a VM extension object "inside" of a VM object. required kwargs: .. code-block:: yaml extension_name: myvmextension virtual_machine_name: myvm settings: {"commandToExecute": "hostname"} optional kwargs: .. code-block:: yaml ...
def create_or_update_vmextension(call=None, kwargs=None): # pylint: disable=unused-argument ''' .. versionadded:: 2019.2.0 Create or update a VM extension object "inside" of a VM object. required kwargs: .. code-block:: yaml extension_name: myvmextension virtual_machine_name: m...
.. versionadded:: 2019.2.0 Stop (deallocate) a VM CLI Examples: .. code-block:: bash salt-cloud -a stop myminion
def stop(name, call=None): ''' .. versionadded:: 2019.2.0 Stop (deallocate) a VM CLI Examples: .. code-block:: bash salt-cloud -a stop myminion ''' if call == 'function': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ...
Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present
def license_present(name): ''' Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if not __salt__['powerpath.has_...
Create the .rpmmacros file in user's home directory
def _create_rpmmacros(runas='root'): ''' Create the .rpmmacros file in user's home directory ''' home = os.path.expanduser('~') rpmbuilddir = os.path.join(home, 'rpmbuild') if not os.path.isdir(rpmbuilddir): __salt__['file.makedirs_perms'](name=rpmbuilddir, user=runas, group='mock') ...
Create the rpm build tree
def _mk_tree(runas='root'): ''' Create the rpm build tree ''' basedir = tempfile.mkdtemp() paths = ['BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'] for path in paths: full = os.path.join(basedir, path) __salt__['file.makedirs_perms'](name=full, user=runas, group='mock') return ...
Get the spec file and place it in the SPECS dir
def _get_spec(tree_base, spec, template, saltenv='base'): ''' Get the spec file and place it in the SPECS dir ''' spec_tgt = os.path.basename(spec) dest = os.path.join(tree_base, 'SPECS', spec_tgt) return __salt__['cp.get_url']( spec, dest, saltenv=saltenv)
Get the distribution string for use with rpmbuild and mock
def _get_distset(tgt): ''' Get the distribution string for use with rpmbuild and mock ''' # Centos adds 'centos' string to rpm names, removing that to have # consistent naming on Centos and Redhat, and allow for Amazon naming tgtattrs = tgt.split('-') if tgtattrs[0] == 'amzn': distse...
Get include string for list of dependent rpms to build package
def _get_deps(deps, tree_base, saltenv='base'): ''' Get include string for list of dependent rpms to build package ''' deps_list = '' if deps is None: return deps_list if not isinstance(deps, list): raise SaltInvocationError( '\'deps\' must be a Python list or comma-s...
Create a source rpm from the given spec file and sources CLI Example: .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec https://pypi.python.org/packages/source/l/lib...
def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base', runas='root'): ''' Create a source rpm from the given spec file and sources CLI Example: .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/salt...
Given the package destination directory, the spec file source and package sources, use mock to safely build the rpm defined in the spec file CLI Example: .. code-block:: bash salt '*' pkgbuild.build mock epel-7-x86_64 /var/www/html https://raw.githubusercontent.com/saltstack/l...
def build(runas, tgt, dest_dir, spec, sources, deps, env, template, saltenv='base', log_dir='/var/log/salt/pkgbuild'): ''' Given the package destination directory, the spec file source and package sources, use mock to ...
Make a package repository and optionally sign packages present Given the repodir, create a ``yum`` repository out of the rpms therein and optionally sign it and packages present, the name is directory to turn into a repo. This state is best used with onchanges linked to your package building states. ...
def make_repo(repodir, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='root', timeout=15.0): ''' Make a package repository and optionally sign packages present Given the repodir, create a `...
Recursively iterate down through data structures to determine output
def display(self, ret, indent, prefix, out): ''' Recursively iterate down through data structures to determine output ''' if isinstance(ret, six.string_types): lines = ret.split('\n') for line in lines: out += '{0}{1}{2}{3}{4}\n'.format( ...
Execute the Thorium runtime
def start(grains=False, grain_keys=None, pillar=False, pillar_keys=None): ''' Execute the Thorium runtime ''' state = salt.thorium.ThorState( __opts__, grains, grain_keys, pillar, pillar_keys) state.start_runtime()
Open the connection to the Junos device, login, and bind to the Resource class
def init(opts): ''' Open the connection to the Junos device, login, and bind to the Resource class ''' opts['multiprocessing'] = False log.debug('Opening connection to junos') args = {"host": opts['proxy']['host']} optional_args = ['user', 'username', ...
Validate and return the connection status with the remote device. .. versionadded:: 2018.3.0
def alive(opts): ''' Validate and return the connection status with the remote device. .. versionadded:: 2018.3.0 ''' dev = conn() thisproxy['conn'].connected = ping() if not dev.connected: __salt__['event.fire_master']({}, 'junos/proxy/{}/stop'.format( opts['proxy'][...
Ping? Pong!
def ping(): ''' Ping? Pong! ''' dev = conn() # Check that the underlying netconf connection still exists. if dev._conn is None: return False # call rpc only if ncclient queue is empty. If not empty that means other # rpc call is going on. if hasattr(dev._conn, '_session'):...
Retry grabbing a URL. Based heavily on boto.utils.retry_url
def _retry_get_url(url, num_retries=10, timeout=5): ''' Retry grabbing a URL. Based heavily on boto.utils.retry_url ''' for i in range(0, num_retries): try: result = requests.get(url, timeout=timeout, proxies={'http': ''}) if hasattr(result, 'text'): r...
Stolen completely from boto.providers
def _convert_key_to_str(key): ''' Stolen completely from boto.providers ''' # IMPORTANT: on PY2, the secret key must be str and not unicode to work # properly with hmac.new (see http://bugs.python.org/issue5285) # # pylint: disable=incompatible-py3-code,undefined-variable return salt.uti...
Pick up the documentation for all of the modules and print it out.
def print_docs(self): ''' Pick up the documentation for all of the modules and print it out. ''' docs = {} for name, func in six.iteritems(self.minion.functions): if name not in docs: if func.__doc__: docs[name] = func.__doc__ ...
Print out the grains
def print_grains(self): ''' Print out the grains ''' grains = self.minion.opts.get('grains') or salt.loader.grains(self.opts) salt.output.display_output({'local': grains}, 'grains', self.opts)
Execute the salt call logic
def run(self): ''' Execute the salt call logic ''' profiling_enabled = self.opts.get('profiling_enabled', False) try: pr = salt.utils.profile.activate_profile(profiling_enabled) try: ret = self.call() finally: sa...
Call the module
def call(self): ''' Call the module ''' ret = {} fun = self.opts['fun'] ret['jid'] = salt.utils.jid.gen_jid(self.opts) proc_fn = os.path.join( salt.minion.get_proc_dir(self.opts['cachedir']), ret['jid'] ) if fun not in self....
Return the data up to the master
def return_pub(self, ret): ''' Return the data up to the master ''' channel = salt.transport.client.ReqChannel.factory(self.opts, usage='salt_call') load = {'cmd': '_return', 'id': self.opts['id']} for key, value in six.iteritems(ret): load[key] = value ...
Execute a remote execution command USAGE: .. code-block:: yaml run_remote_ex: local.cmd: - tgt: '*' - func: test.ping run_remote_ex: local.cmd: - tgt: '*' - func: test.sleep - arg: - 30 run...
def cmd(name, tgt, func, arg=(), tgt_type='glob', ret='', kwarg=None, **kwargs): ''' Execute a remote execution command USAGE: .. code-block:: yaml run_remote_ex: local.cmd: - tgt: '*' - func: test.ping ...
Sets global variables _OS_IDENTITY_API_VERSION and _TENANT_ID depending on API version.
def _api_version(profile=None, **connection_args): ''' Sets global variables _OS_IDENTITY_API_VERSION and _TENANT_ID depending on API version. ''' global _TENANT_ID global _OS_IDENTITY_API_VERSION try: if float(__salt__['keystone.api_version'](profile=profile, **connection_args).stri...
Ensure that the keystone user is present with the specified properties. name The name of the user to manage password The password to use for this user. .. note:: If the user already exists and a different password was set for the user than the one specified he...
def user_present(name, password, email, tenant=None, enabled=True, roles=None, profile=None, password_reset=True, project=None, **connection_args): ''' Ensure ...
Ensure that the keystone user is absent. name The name of the user that should not exist
def user_absent(name, profile=None, **connection_args): ''' Ensure that the keystone user is absent. name The name of the user that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" is already absent'.format(name...
Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for this tenant
def tenant_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for...
Ensure that the keystone tenant is absent. name The name of the tenant that should not exist
def tenant_absent(name, profile=None, **connection_args): ''' Ensure that the keystone tenant is absent. name The name of the tenant that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" is already a...
Ensures that the keystone project exists Alias for tenant_present from V2 API to fulfill V3 API naming convention. .. versionadded:: 2016.11.0 name The name of the project to manage description The description to use for this project enabled Availability state for thi...
def project_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone project exists Alias for tenant_present from V2 API to fulfill V3 API naming convention. .. versionadded:: 2016.11.0 name The name of the projec...
Ensures that the keystone role exists name The name of the role that should be present
def role_present(name, profile=None, **connection_args): '''' Ensures that the keystone role exists name The name of the role that should be present ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" already exists'.format(name)} ...
Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the service
def service_present(name, service_type, description=None, profile=None, **connection_args): ''' Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the ...
Ensure the specified endpoints exists for service name The Service name publicurl The public url of service endpoint (for V2 API) internalurl The internal url of service endpoint (for V2 API) adminurl The admin url of the service endpoint (for V2 API) region ...
def endpoint_present(name, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Ensure the s...
Ensure that the endpoint for a service doesn't exist in Keystone catalog name The name of the service whose endpoints should not exist region (optional) The region of the endpoint. Defaults to ``RegionOne``. interface The interface type, which describes the visibility of ...
def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args): ''' Ensure that the endpoint for a service doesn't exist in Keystone catalog name The name of the service whose endpoints should not exist region (optional) The region of the endpoint. Defaults to...
Run 'chkconfig --add' for a service whose script is installed in /etc/init.d. The service is initially configured to be disabled at all run-levels.
def _chkconfig_add(name): ''' Run 'chkconfig --add' for a service whose script is installed in /etc/init.d. The service is initially configured to be disabled at all run-levels. ''' cmd = '/sbin/chkconfig --add {0}'.format(name) if __salt__['cmd.retcode'](cmd, python_shell=False) == 0: ...
Return True if the service is a System V service (includes those managed by chkconfig); otherwise return False.
def _service_is_sysv(name): ''' Return True if the service is a System V service (includes those managed by chkconfig); otherwise return False. ''' try: # Look for user-execute bit in file mode. return bool(os.stat( os.path.join('/etc/init.d', name)).st_mode & stat.S_IXUS...
Return True if the service is managed by chkconfig.
def _service_is_chkconfig(name): ''' Return True if the service is managed by chkconfig. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) return __salt__['cmd.retcode'](cmdline, python_shell=False, ignore_retcode=True) == 0
Return True if the sysv (or chkconfig) service is enabled for the specified runlevel; otherwise return False. If `runlevel` is None, then use the current runlevel.
def _sysv_is_enabled(name, runlevel=None): ''' Return True if the sysv (or chkconfig) service is enabled for the specified runlevel; otherwise return False. If `runlevel` is None, then use the current runlevel. ''' # Try chkconfig first. result = _chkconfig_is_enabled(name, runlevel) if...
Return ``True`` if the service is enabled according to chkconfig; otherwise return ``False``. If ``runlevel`` is ``None``, then use the current runlevel.
def _chkconfig_is_enabled(name, runlevel=None): ''' Return ``True`` if the service is enabled according to chkconfig; otherwise return ``False``. If ``runlevel`` is ``None``, then use the current runlevel. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) result = __salt__['cmd.run_al...
Enable the named sysv service to start at boot. The service will be enabled using chkconfig with default run-levels if the service is chkconfig compatible. If chkconfig is not available, then this will fail.
def _sysv_enable(name): ''' Enable the named sysv service to start at boot. The service will be enabled using chkconfig with default run-levels if the service is chkconfig compatible. If chkconfig is not available, then this will fail. ''' if not _service_is_chkconfig(name) and not _chkconfig_...
Delete the named sysv service from the system. The service will be deleted using chkconfig.
def _sysv_delete(name): ''' Delete the named sysv service from the system. The service will be deleted using chkconfig. ''' if not _service_is_chkconfig(name): return False cmd = '/sbin/chkconfig --del {0}'.format(name) return not __salt__['cmd.retcode'](cmd)
Delete an upstart service. This will only rename the .conf file
def _upstart_delete(name): ''' Delete an upstart service. This will only rename the .conf file ''' if HAS_UPSTART: if os.path.exists('/etc/init/{0}.conf'.format(name)): os.rename('/etc/init/{0}.conf'.format(name), '/etc/init/{0}.conf.removed'.format(name)) r...
Return list of sysv services.
def _sysv_services(): ''' Return list of sysv services. ''' _services = [] output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False) for line in output.splitlines(): comps = line.split() try: if comps[1].startswith('0:'): _services.appe...
Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=sysvinit
def get_enabled(limit=''): ''' Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=s...
Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit
def get_all(limit=''): ''' Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit '''...
Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*' service.available sshd limit=sysvinit
def available(name, limit=''): ''' Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*...
The inverse of service.available. Return True if the named service is not available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.missing sshd salt '*' service.missing sshd limit=upstart salt '*' ser...
def missing(name, limit=''): ''' The inverse of service.available. Return True if the named service is not available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.missing sshd salt '*' service.missin...
Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name>
def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' if _service_is_upstart(name): cmd = 'start {0}'.format(name) else: cmd = '/sbin/service {0} start'.format(name) return not __salt__['cmd...
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' if _service_is_upstart(name): cmd = 'stop {0}'.format(name) else: cmd = '/sbin/service {0} stop'.format(name) return not __salt__['cmd.retc...
Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name>
def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if _service_is_upstart(name): cmd = 'restart {0}'.format(name) else: cmd = '/sbin/service {0} restart'.format(name) return not __salt_...
Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name>
def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' if _service_is_upstart(name): cmd = 'reload {0}'.format(name) else: cmd = '/sbin/service {0} reload'.format(name) return not __salt__['c...
Check for specified command name in search path
def _check_repo_sign_utils_support(name): ''' Check for specified command name in search path ''' if salt.utils.path.which(name): return True else: raise CommandExecutionError( 'utility \'{0}\' needs to be installed or made available in search path'.format(name) )
Get build environment overrides dictionary to use in build process
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for k...
Get repo environment overrides dictionary to use in repo options process env A dictionary of variables to define the repository options Example: .. code-block:: yaml - env: - OPTIONS : 'ask-passphrase' .. warning:: The above illustrates a ...
def _get_repo_options_env(env): ''' Get repo environment overrides dictionary to use in repo options process env A dictionary of variables to define the repository options Example: .. code-block:: yaml - env: - OPTIONS : 'ask-passphrase' .. war...
Get repo environment overrides dictionary to use in repo distributions process env A dictionary of variables to define the repository distributions Example: .. code-block:: yaml - env: - ORIGIN : 'jessie' - LABEL : 'salt debian' ...
def _get_repo_dists_env(env): ''' Get repo environment overrides dictionary to use in repo distributions process env A dictionary of variables to define the repository distributions Example: .. code-block:: yaml - env: - ORIGIN : 'jessie' ...
Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illus...
def _create_pbuilders(env, runas='root'): ''' Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'noche...
Get the named sources and place them into the tree_base
def _get_src(tree_base, source, saltenv='base'): ''' Get the named sources and place them into the tree_base ''' parsed = _urlparse(source) sbase = os.path.basename(source) dest = os.path.join(tree_base, sbase) if parsed.scheme: __salt__['cp.get_url'](source, dest, saltenv=saltenv) ...
Create a platform specific source package from the given platform spec/control file and sources CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar...
def make_src_pkg(dest_dir, spec, sources, env=None, saltenv='base', runas='root'): ''' Create a platform specific source package from the given platform spec/control file and sources CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ ...
Given the package destination directory, the tarball containing debian files (e.g. control) and package sources, use pbuilder to safely build the platform package CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg deb-8-x86_64 /var/www/html https://ra...
def build(runas, tgt, dest_dir, spec, sources, deps, env, template, saltenv='base', log_dir='/var/log/salt/pkgbuild'): # pylint: disable=unused-argument ''' Given the package destination directory, the tarball containing ...